Adding custom property to marker (Google Map Android API V2)

泄露秘密 提交于 2019-12-02 17:38:51

You cannot directly extend Marker, because it is a final class, but you have some options:

0) As of Google Maps Android API v2 version 9.4.0, you can use Marker::getTag and Marker::setTag. This is most likely the preferred option.

1) Create a map to store all additional information:

private Map<Marker, MyData> allMarkersMap = new HashMap<Marker, MyData>();

When creating a marker, add it to this map with your data:

Marker marker = map.addMarker(...);
allMarkersMap.put(marker, myDataObj);

Later in your render function:

MyData myDataObj = allMarkersMap.get(marker);
if (myDataObj.customProp) { ...

2) Another way would be to use Marker.snippet to store all the info as a String and later parse it, but that's kinda ugly and unmaintainable solution.

3) Switch from plain Google Maps Android API v2 to Android Maps Extensions.

This is very similar to point 1, but you can directly store MyData into marker, using

marker.setData(myDataObj);

and later:

MyData myDataObj = (MyData) marker.getData();

I used Marker.setTag(Object o) and .getTag() to pass my custom location obj. to the Marker. Of course the Object can be any kind of object you want.

Marker m = googleMap.addMarker(new MarkerOptions()
                .position( ... )
                // setTag is not part of MarkerOptions so can't be defined here
              );
m.setTag(location); // Marker.setTag()

And accessing that obj. in InfoWindowAdapter is easy:

@Override
public View getInfoContents(Marker marker) {
   ...
   Object o = marker.getTag();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!