How to save information of markers of Map v2 so that it can be retrieve on marker click

巧了我就是萌 提交于 2019-12-04 15:31:37
Pavel Dudka

Unfortunately you cannot add metadata to your markers. What you need to do instead - is to save markers as you add them to some data structure in form of map (<Marker, Model>), so you can retrieve model based on marker.

Let's assume you have a Model class which defines Hotel information. In this case, you can have a map of objects to keep track of your markers:

Map<Marker, Model> markerMap = new HashMap<Marker, Model>();

Now as you add markers, just put them in this map:

public void addMarker(Model hotelModel) {

    if (null != googleMap) {
        Marker hotelMarker = MyMapFragment.this.googleMap.addMarker(new MarkerOptions()
                        .position(new LatLng(hotelModel.getLat(), hotelModel.getLon()))
                        .title(hotelModel.getTitle())
        );

        markerMap.add(hotelMarker, hotelModel);
    }
}

Now when marker is clicked, you can get hotel model based on the marker object:

@Override
public boolean onMarkerClick (Marker marker) {
    Model hotelModel = markerMap.get(marker);
    if(hotelModel != null) {
        Log.d("test", "Hotel "+hotelModel.getTitle()+" is clicked"); 
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!