首页 > 解决方案 > 当用户单击 mMap.setOnMarkerClickListener 时如何发送值?

问题描述

当用户单击 mMap.setOnMarkerClickListener 时如何发送值?

我不知道为什么当用户点击谷歌地图标记时我总是得到相同的值。

这是 Firebase 数据

"Campsite" : {
    "-MfS3VgBGROs_afkVrjl" : {
      "CamperSiteAddress" : "Charles St & Esplanade W, Triabunna TAS 7190, Australia",
      "CamperSiteID" : "-MfS3VgBGROs_afkVrjl",
      "Counrty" : "Australia",
      "CamperSiteImages" : [
 "https://firebasestorage.googleapis.com/v0/b/campingau-6b84d.appspot.com/o/CampSitePhotos%2F1627206575487.null?alt=media&token=bff07bd4-fd17-4099-a0d7-db0418311425", 
"https://firebasestorage.googleapis.com/v0/b/campingau-6b84d.appspot.com/o/CampSitePhotos%2F1627206580478.null?alt=media&token=995bf983-0ee8-4f25-af3f-921aa5b0077c", 
"https://firebasestorage.googleapis.com/v0/b/campingau-6b84d.appspot.com/o/CampSitePhotos%2F1627206584072.null?alt=media&token=137b87a9-f6fb-4f75-9d53-7c3efda8cda4" 
],
      "CamperSiteLatitude" : -42.508695,
      "CamperSiteLongitude" : 147.916617,
      "CamperSiteName" : "Encampment Cove Walk"
    }

这是我的代码

 DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Campsite");
        Query query = reference.orderByChild("country").equalTo(country);
        query.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildName) {
                list.clear();
                List<String> mapImage = (List<String>) dataSnapshot.child("CamperSiteImages").getValue();
                Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                Double lat = (Double)map.get("CamperSiteLatitude");
                Double lng = (Double)map.get("CamperSiteLongitude");
                LatLng newLocation = new LatLng(lat, lng);
                String CampSiteName = (String) map.get("CamperSiteName");
                String CampSitePostID = (String) map.get("CamperSiteID");
                String CampSiteType= (String) map.get("type");
                String CampSiteImage = mapImage.get(0);
                list.add(String.valueOf(newLocation));
                for(int i = 0; i < list.size(); i++){
                    try{
                        //bitmap = Ion.with(getApplicationContext()).load(CampSiteImage).withBitmap().fitCenter().resize(120,120).asBitmap().get();
                    } catch (Exception e){
                        e.printStackTrace();
                    }
mMap.addMarker(new MarkerOptions().position(newLocation).title(CampSiteName).icon(BitmapDescriptorFactory.fromResource(icon)));
                    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {
                            Toast.makeText(getContext(),CampSitePostID, Toast.LENGTH_SHORT).show();
                            return false;
                        }
                    });
                }
                progressDialog.dismiss();
            }

现在,当我单击标记时,标题是正确的,但我总是得到相同的 CamperSiteID。如何解决这个问题?

标签: androidgoogle-mapsgoogle-maps-markers

解决方案


When you add a marker it returns a Marker object which has a field available for the application to associate with the marker - called the tag field (accessed using getTag and setTag). This tag field can then be retrieved in the onMarkerClick callback.

So in your code you could do this:

Marker m = mMap.addMarker(new MarkerOptions().position(newLocation).title(CampSiteName).icon(BitmapDescriptorFactory.fromResource(icon)));
m.setTag(CampSitePostID);

and in the marker click callback:

public boolean onMarkerClick(Marker marker) {
    String campSiteID = "?";
    if (marker.getTag() != null) {
        campSiteID = (String) marker.getTag();
    }
    //...use campSiteID instead of CampSitePostID
}

Here's more info from the documentation: https://developers.google.com/maps/documentation/android-sdk/marker#associate_data_with_a_marker.

If your application has more data to associate than a simple String then more complex solutions can be implemented:

  1. Since the tag is an object instance you can associate any object of your choosing such as a class with many properties (or even the map variable in your example)
  2. Since each marker has a unique id field (m.getId()) you can use that field as a key into your own map implementation to access associated data. Marker ids are unique for the current instance of the map (the numbering is reset when the app is restarted or the map is reinitialized).
  3. As combination of (1) and (2) you can create your own mapping key and set that as the tag value and use that key to map into your own data.

Notes:

  1. The map has only one marker click event handler. In your code you are setting the marker click event handler on every firebase callback. This is unnecessary and this leads to the likely result where the last marker added is the CampSitePostId used for any marker click.
  2. In your onChildAdded you first list.clear() which empties the list and then perform one list.add and then loop on the size of the list; but it will always be of size 1.

推荐阅读