I have a simple "Place" class:
public class Plac{
String name;
int id;
LatLng latlng;
public Product(String name, int id, LatLng latlng) {
this.name = name;
this.id= id;
this.latlng = latlng;
}
}
and I'm adding "Places" to an ArrayList like this: (Note the names are not unique)
ArrayList<Place> places = new ArrayList<Place>();
places.add(new Place("McDonald's", 1));
places.add(new Place("McDonald's", 2));
places.add(new Place("McDonald's", 3));
I'm adding markers to my Google Map like this:
for(Place place : places)
map.addMarker(new MarkerOptions().position(place.latlng).title(place.name);
I want to know how to add a listener for each marker that is being added to the map. I've tried to use
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
}
});
which works, however, the only thing I can do with this is get the title of the marker which is not unique so I can't really find which EXACT "Place" object is being clicked on. Any ideas? Thanks
When you create an info window, it is not displayed automatically on the map. To make the info window visible, you must call the open() method on the InfoWindow , passing an InfoWindowOpenOptions object literal specifying the following options: map specifies the map or Street View panorama on which to open.
You can modify the whole InfoWindow using jquery alone... var popup = new google. maps. InfoWindow({ content:'<p id="hook">Hello World!
You could just use the LatLng
object returned from calling getPosition()
on the Marker
to uniquely identify each Marker
, and find the match in your places
array.
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
LatLng latLon = marker.getPosition();
//Cycle through places array
for(Place place : places){
if (latLon.equals(place.latlng)){
//match found! Do something....
}
}
}
});
Documentation:
https://developer.android.com/reference/com/google/android/gms/maps/model/Marker.html
http://developer.android.com/reference/com/google/android/gms/maps/model/MarkerOptions.html
I suggest using a HashMap
.
private HashMap<Marker, Place> markerMap = new HashMap<Marker, Place>();
In your loop:
for(Place place : places){
MarkerOption marker =new MarkerOptions().position(place.latlng).title(place.name);
map.addMarker(marker);
markerMap.put(marker, place)
}
In your Listener:
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Place place = markerMap.get(marker);// here you get your exact Place Object
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With