gaurav gaurav - 4 months ago 31
Android Question

on marker click in Maps

I am trying to get the marker that is clicked but i'm only getting the last marker name
I wish to apply dialog box on the selected marker but it's getting the last marker only

for(int i=0;i<objectResults.length();i++){
JSONObject place=objectResults.getJSONObject(i);
String store_id=place.getString("id");
final String place_name=place.getString("name");
double latitude1, longitude1;
latitude1=place.getJSONObject("geometry").getJSONObject("location").getDouble("lat");
longitude1=place.getJSONObject("geometry").getJSONObject("location").getDouble("lng");

MarkerOptions markerOptions=new MarkerOptions();
LatLng latLng=new LatLng(latitude1,longitude1);
markerOptions.position(latLng);
markerOptions.title(place_name);
mMap.addMarker(markerOptions);

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(getContext(),"YOU CLICKED ON "+place_name,Toast.LENGTH_LONG).show();
return false;
}
);
}


thanks in Advance.

Answer

You should get the title of the clicked marker using getTitle() where is storage place_name. like this:

   mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
       @Override
       public boolean onMarkerClick(Marker marker) {
           Toast.makeText(getContext(),"YOU CLICKED ON "+marker.getTitle(),Toast.LENGTH_LONG).show();
           return false;
           }
       );
  }