当前位置: 首页 > 知识库问答 >
问题:

我想在android的nextactivity中点击标记时发送json数据

后星河
2023-03-14

我是新的,我正在努力发送数据点击标记在下一个活动,请帮助我。如有任何帮助,不胜感激

public class CompanyOutletFragment extends Fragment implements ConnectionCallbacks, OnConnectionFailedListener,LocationListener {

    private ProgressDialog progressDialog;
    private GoogleMap googleMap;

    private Location mCurrentLocation;
    private LocationRequest locationRequest;
    private int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private GoogleApiClient googleApiClient;

    float latitude1, longitude1;


    String latitude,longitude;

    Geocoder geocoder;
    List<Address> addresses;


    String mobileNumber,contactPerson,id;

    JSONObject datavalues;

    HashMap<String,String> outlet;//in this i am putting key- value pair

    ArrayList<HashMap<String,String>> add1;//here i am adding all the values

    HashMap<String, HashMap> extraMarkerInfo=new  HashMap<String, HashMap>();//here i am getting id relted to laatitude and longitude

    //

    private Marker marker;

    public static final String TAG_CONTACTPERSON = "contactPerson";

    public static final String TAG_LATITUDE= "latitude";

    public static final String TAG_LONGITUDE = "longitude";

    public static final String TAG_ID = "id";


    String companyurl = "http://client.zoneonedigital.com/carwash_v2/api/ws/controller/?access=true&action=get_franchise_list&sHavingCompanyOwnedOutlet=1";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View rootView = null;
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_companyoutlet, container, false);
        }
        initilizeMap(rootView);



        getCompanyList();


        getLocation(rootView);
        return rootView;
    }

    private void getCompanyList() {
        //  showdialouge();
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        CustomRequest jsonrequest = new CustomRequest(companyurl, null, this.reponseSuccessListener(), this.errorListener());
        requestQueue.add(jsonrequest);

        // TODO Auto-generated method stub

    }

    private Response.ErrorListener errorListener() {
        // TODO Auto-generated method stub
        return new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                //   dissmissdialouge();

            }
        };
    }


    private void getNearbyLocation(View v, String latitude1, String longitude1) {
        HashMap<String, String> params = new HashMap<>();
        params.put("latitude", String.valueOf(latitude1));
        params.put("longitude", String.valueOf(longitude1));
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        CustomRequest jsonRequest = new CustomRequest(Request.Method.POST, Config.URL_GET_NEEARBY_FRENCHISE_LIST, params,
                this.createNearSuccessListner(), this.errorNearListner());
        requestQueue.add(jsonRequest);
    }

    private Response.Listener<JSONObject> createNearSuccessListner() {
        return new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d("location", response.toString());
                try {
                    if (response.getBoolean("status") == true) {

                    } else {
                        Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        };
    }

    private Response.ErrorListener errorNearListner() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getActivity(), volleyError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        };
    }


    private Response.Listener<JSONObject> reponseSuccessListener() {
        // TODO Auto-generated method stub
        return new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                // TODO Auto-generated method stub
                //    dissmissdialouge();
                Log.d("frenchosilist", response.toString());
                try {
                    if (response.getBoolean("status")) {
                        JSONArray data = response.getJSONArray("data");

                        add1=new ArrayList<HashMap<String,String>>();

                     outlet = new HashMap<String,String>();

                        if (data.length() > 0) {
                            for (int i = 0; i < data.length(); i++) {
                                 datavalues = data.getJSONObject(i);
                                FrenchiseModel fm = new FrenchiseModel();
                                // fm.setFrenchiseID(Integer.valueOf(datavalues.getString("id")));
                                fm.setFrenchiseName(datavalues.getString("franchiseName"));

                                fm.setContactPerson(datavalues.getString("contactPerson"));

                                fm.setMobileNumber(datavalues.getString("mobileNumber"));

                                fm.setFrenchiseLang(datavalues.getString("latitude"));

                                fm.setFrenchiseLat(datavalues.getString("longitude"));



                                latitude1 = Float.valueOf(datavalues.getString("latitude"));

                                longitude1 = Float.valueOf(datavalues.getString("longitude"));

                                latitude = datavalues.getString("latitude");

                                longitude = datavalues.getString("longitude");

                                id=datavalues.getString("id");

                                System.out.println("All id's Are"+ id);

                                contactPerson=datavalues.getString("contactPerson");

                                System.out.println("Contact Person Are"+ contactPerson);

                               mobileNumber=datavalues.getString("mobileNumber");

                                System.out.println("Contact Mobile Are"+  mobileNumber);

                                fm.setFrenchiseLat(datavalues.getString("latitude"));
                                fm.setFrenchiseLang(datavalues.getString("longitude"));

                                outlet.put(TAG_LONGITUDE,longitude);

                                outlet.put(TAG_LATITUDE,latitude);

                                outlet.put(TAG_ID,id);

                                outlet.put(TAG_CONTACTPERSON,contactPerson);

                                add1.add(outlet);

                                System.out.println("total values Are"+add1);

                                if (googleMap != null)
                                    googleMap.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(datavalues.getString("latitude")), Double.valueOf(datavalues.getString("longitude")))).title(datavalues.getString("franchiseName")).draggable(true).icon(BitmapDescriptorFactory.fromResource(R.drawable.car_map)));
                            }


                        }
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    //   dissmissdialouge();
                    e.printStackTrace();
                }

            }
        };
    }

    private void getLocation(View rootView) {
        // TODO Auto-generated method stub
        if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(getActivity()).addApi(LocationServices.API)
                    .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
            googleApiClient.connect();

            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);

            // **************************
            builder.setAlwaysShow(true); // this is the key ingredient
            // **************************

            PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
                    .checkLocationSettings(googleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();
                    final LocationSettingsStates state = result.getLocationSettingsStates();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.SUCCESS:
                            // All location settings are satisfied. The client can
                            // initialize location
                            // requests here.

                            break;
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            // Location settings are not satisfied. But could be
                            // fixed by showing the user
                            // a dialog.
                            try {
                                // Show the dialog by calling
                                // startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult(getActivity(), 1000);
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            // Location settings are not satisfied. However, we have
                            // no way to fix the
                            // settings so we won't show the dialog.
                            break;
                    }
                }
            });
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d("location", "onStart fired ..............");
        googleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d("location", "onStop fired ..............");
        googleApiClient.disconnect();
        Log.d("location", "isConnected ...............: " + googleApiClient.isConnected());
    }

    private void initilizeMap(View rootView) {
        if (googleMap == null) {

            try {
                googleMap = getMapFragment().getMap();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), "MAP IS STARTED", Toast.LENGTH_SHORT).show();


                //final LatLng PERTH = new LatLng(-31.90, 115.86);




                if (mCurrentLocation != null) {




                    for (HashMap<String, String> hashMap : add1) {

                        Marker marker=googleMap.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(hashMap.get(latitude)), Double.valueOf(hashMap.get(longitude)))));

                        getNearbyLocation(rootView, String.valueOf(hashMap.get(latitude)), String.valueOf(hashMap.get(longitude)));



                        Log.d("latitude", String.valueOf(hashMap.get(latitude)));
                        Log.d("langitude", String.valueOf(hashMap.get(longitude)));

                        HashMap<String, String> data = new HashMap<String, String>();

                        data.put("contactPerson",hashMap.get(contactPerson));

                        data.put("mobilenumber",hashMap.get(mobileNumber));

                        extraMarkerInfo.put(marker.getId(),data);

                        System.out.println("Extrainfo id are"+ marker.getId()+"and data are"+data);

                    }

               //     Log.d("latitude", String.valueOf(mCurrentLocation.getLatitude()));
                //    Log.d("langitude", String.valueOf(mCurrentLocation.getLongitude()));
                 //   googleMap.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(mCurrentLocation.getLatitude()), Double.valueOf(mCurrentLocation.getLongitude()))).draggable(true).icon(BitmapDescriptorFactory.fromResource(R.drawable.car_map)));

                  //  googleMap.addMarker(new MarkerOptions().position( ))

                //    getNearbyLocation(rootView, String.valueOf(mCurrentLocation.getLatitude()), String.valueOf(mCurrentLocation.getLongitude()));





                  //  data.put("contactperson",hashMap.get(TAG_Location));
                 //   data.put(TAG_Company,hashMap.get(TAG_Company));




                }


                //  googleMap.addMarker(new MarkerOptions().position(PERTH).draggable(true).icon(BitmapDescriptorFactory.fromResource(R.drawable.car_map)));
                //  CameraPosition cameraPosition = new CameraPosition.Builder().target(PERTH).zoom(12).build();

                //  googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }

            googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick(Marker marker) {

                     String title = marker.getTitle();

                    HashMap<String, String> marker_data = extraMarkerInfo.get(marker.getId());


                    System.out.println("Marker all values are"+marker_data);

                    String contactperson = marker_data.get(TAG_CONTACTPERSON);

                    System.out.println("Marker contact person values are"+  contactperson);

                    System.out.println("Marker name is"+ title);

                    if(marker.getTitle().equals(title)){
                        Intent intent1 = new Intent(getContext(), Booking.class);
                        intent1.putExtra("contactPerson", contactperson);
                        startActivity(intent1);

                    }


                }
            });

        }

    }

    private SupportMapFragment getMapFragment() {
        // TODO Auto-generated method stub
        FragmentManager fm = null;

        Log.d("tag", "sdk: " + Build.VERSION.SDK_INT);
        Log.d("tag", "release: " + Build.VERSION.RELEASE);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            Log.d("tag", "using getFragmentManager");
            fm = getFragmentManager();
        } else {
            Log.d("Fragmenttype", "using getChildFragmentManager");
            fm = getChildFragmentManager();
        }

        return (SupportMapFragment) fm.findFragmentById(R.id.companymapmap);
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnected(Bundle arg0) {
        // TODO Auto-generated method stub
        Log.d("location", "onConnected - isConnected ...............: " + googleApiClient.isConnected());
        displaylocation();

    //startLocationUpdates();

    }

    protected void startLocationUpdates() {
        // TODO Auto-generated method stub
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }
    protected void stoplocationupdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        // TODO Auto-generated method stub
        googleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        mCurrentLocation = location;
        displaylocation();

    }
    private void displaylocation() {
        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(
                googleApiClient);
        if (mCurrentLocation != null) {
            Log.d("latitude",String.valueOf(mCurrentLocation.getLatitude()));
            Log.d("langitude",String.valueOf(mCurrentLocation.getLongitude()));

           googleMap.addMarker(new MarkerOptions().position(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude())).draggable(true).title("Manish"));
            CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude())).zoom(12).build();

            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            getAddressfromlocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());

        }



        dissmissdialouge();
    }
    protected synchronized void bulidgoogleapiclient() {
        googleApiClient = new GoogleApiClient.Builder(getActivity()).addApi(LocationServices.API)
                .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
        googleApiClient.connect();
    }
    protected void createlocationrequest() {
        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        locationRequest.setSmallestDisplacement(10);

    }

    private boolean checkplayservices()
    {
        int resultcode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if(resultcode != ConnectionResult.SUCCESS)
        {
            if(GooglePlayServicesUtil.isUserRecoverableError(resultcode))
            {
                GooglePlayServicesUtil.getErrorDialog(resultcode, getActivity(), PLAY_SERVICES_RESOLUTION_REQUEST).show();
            }
            else
            {
                Toast.makeText(getActivity(), "This is not supported to use google play services", Toast.LENGTH_SHORT).show();

            }

            return false;
        }
        return true;

    }
    private void showdialouge() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("WAIT...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }
    private void dissmissdialouge() {
        if(progressDialog != null)
        {
            progressDialog.dismiss();
        }
    }
    protected void getAddressfromlocation(double lat, double lang) {
        geocoder = new Geocoder(getActivity(), Locale.getDefault());

        try {
            addresses = geocoder.getFromLocation(lat, lang, 1);

            String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
            String city = addresses.get(0).getLocality();
            String state = addresses.get(0).getAdminArea();
            String country = addresses.get(0).getCountryName();
            String postalCode = addresses.get(0).getPostalCode();
            String knownName = addresses.get(0).getFeatureName();
            Log.d("address", address);
          //  this.address.setText(address);
          //  this.address.setTextSize(16);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            dissmissdialouge();
            e.printStackTrace();
        } // Here 1 represent max location result to returned, by documents it recommended 1 to 5

    }

}

共有1个答案

司徒宇
2023-03-14

我这部分我正面临着问题...

private void initilizeMap(View rootView) {

    if (googleMap == null) {

        try {
            googleMap = getMapFragment().getMap();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getContext(), "MAP IS STARTED", Toast.LENGTH_SHORT).show();
            //final LatLng PERTH = new LatLng(-31.90, 115.86)
            if (mCurrentLocation != null) {

                for (HashMap<String, String> hashMap : add1) {

                    Marker marker=googleMap.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(hashMap.get(latitude)), Double.valueOf(hashMap.get(longitude)))));
                    getNearbyLocation(rootView, String.valueOf(hashMap.get(latitude)), String.valueOf(hashMap.get(longitude)));
                    Log.d("latitude", String.valueOf(hashMap.get(latitude)));
                    Log.d("langitude", String.valueOf(hashMap.get(longitude)));
                    HashMap<String, String> data = new HashMap<String, String>();
                    data.put("contactPerson",hashMap.get(contactPerson));
                    data.put("mobilenumber",hashMap.get(mobileNumber));
                    extraMarkerInfo.put(marker.getId(),data);
                    System.out.println("Extrainfo id are"+ marker.getId()+"and data are"+data);

                }

               //     Log.d("latitude", String.valueOf(mCurrentLocation.getLatitude()));
               //    Log.d("langitude", String.valueOf(mCurrentLocation.getLongitude()));
               //   googleMap.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(mCurrentLocation.getLatitude()), Double.valueOf(mCurrentLocation.getLongitude()))).draggable(true).icon(BitmapDescriptorFactory.fromResource(R.drawable.car_map)));
               //  googleMap.addMarker(new MarkerOptions().position( ))
               //    getNearbyLocation(rootView, String.valueOf(mCurrentLocation.getLatitude()), String.valueOf(mCurrentLocation.getLongitude()));
               //  data.put("contactperson",hashMap.get(TAG_Location));
              //   data.put(TAG_Company,hashMap.get(TAG_Company));
            }


            //  googleMap.addMarker(new MarkerOptions().position(PERTH).draggable(true).icon(BitmapDescriptorFactory.fromResource(R.drawable.car_map)));
            //  CameraPosition cameraPosition = new CameraPosition.Builder().target(PERTH).zoom(12).build();
            //  googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        }

        googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {

                 String title = marker.getTitle();

                HashMap<String, String> marker_data = extraMarkerInfo.get(marker.getId());


                System.out.println("Marker all values are"+marker_data);

                String contactperson = marker_data.get(TAG_CONTACTPERSON);

                System.out.println("Marker contact person values are"+  contactperson);

                System.out.println("Marker name is"+ title);

                if(marker.getTitle().equals(title)){
                    Intent intent1 = new Intent(getContext(), Booking.class);
                    intent1.putExtra("contactPerson", contactperson);
                    startActivity(intent1);

                }


            }
        });

    }

}
 类似资料:
  • 嗨,我有问题,如何实现点击标记的信息窗口?问题是我在地图上有很多标记,如果单击信息窗口,每个标记都有另一个活动<代码>在此处输入代码 以下是示例 标记1----- 我尝试了很多代码但没有解决

  • 我正在用谷歌地图在Android上做一个小项目。我有一个问题-它是可能使标记拖动与一次点击它,而不是长按后。例如:我点击标记,它改变了图标,我可以拖动它在地图的任何地方,然后再点击一次,他就不能再拖动了,并且把它的图标改回来了?(即使松开标记器,标记器也必须从第一次点击到第二次点击时始终可拖动)

  • 所以我试图让我的应用程序发送短信自动给给定的号码时,用户按下按钮。 我可以让它打开messenger并编写文本,但我不能让它自动发送。 我的代码如下(我想最重要的部分); 那么,我怎样才能让它发送短信呢? 顺便说一句,我添加了权限:“Android。权限。发送短信”

  • 我想在单击按钮后更改背景

  • 我有一张地图,上面有很多自定义的大标记。现在,我希望允许用户在地图上创建路径(显示为折线,稍后保存为地理坐标对列表)。 如果用户单击地图,我可以使用地图的setOnMapClickedListener方法收集这些位置。但是如果用户点击一个标记(setOnMarkerClickedListener),我只能检索标记的位置(通常是标记的ancor的位置)。