Maps API v2 with different marker actions

丶灬走出姿态 提交于 2019-11-30 01:05:09

I have run into this problem as well. My solution was:

private Map<Marker, MyModel> markerMap = new HashMap<>();
private GoogleMap mMap;

private void doMarkers(){
    MarkerOptions opt = new MarkerOptions();
    //Fill out opt from MyModel
    Marker marker = mMap.addMarker(opt);
    markerMap.put(marker, myModel);
}

and then in the OnMarkerClickListener callback, pull your model out of the HashMap using the clicked marker. There is also a method Marker.getId() which for some reason returns a string. I don't understand why you can't specify an int id when you make the marker, or why you can't access the marker object before you add it to the map.

UPDATE: After almost 4 years Google have added a method Marker.setTag(Object tag) to associate arbitrary data with a marker.

Ok here is a solution which I decided to use and AFAIK should work for any situation:

private HashMap<String, MyModel> markers= new HashMap<String, MyModel>();


MyModel item = ...
MarkerOptions markerOptions = ...
markers.put(mMap.addMarker(markerOptions).getId(), item);



@Override
public void onInfoWindowClick(Marker marker) {
   MyModel mapItem = (MyModel) markers.get(marker.getId());.
   ...
}
ignacio_gs

You can use the marker's getId method

You can use the HashMarker like that. In this example y charge points in Arraylist and each points cointaints a new ArrayList with coordinates. And the idea is you get de point ID.

Create a HashMap

Markers = new HashMap();

Then you create a Marker and add to the map

final Marker marker = map.addMarker(new MarkerOptions().position(new LatLng(coordinates.get(j).getLat(),coordinates.get(j).getLon())).title(point.getName()));

Then you can save the point id with de marker value

Markers.put(marker, point.getId());

And final you can get the id value when you click the InfoWindow

public void onInfoWindowClick(Marker marker) {

    final long id = Marcadores.get(marker);
    Log.e("Real Marker ID", id+"");
}

OR

When you click the marker

public boolean onMarkerClick(Marker arg0) {

    final long id = Marcadores.get(marker);
    Log.e("Real Marker ID", id+"");
    return false;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!