Gheraibia Mohamed Yacine Gheraibia Mohamed Yacine - 6 months ago 56
Android Question

oninfowindowclick used only with only marker info in case of multiple markers

I've made a loop to create multiple markers , but the onInfoWindowClickListener works for all the markers with one parameters

for ( i = 0; i < MyArrListx.size(); i++) {

n = Double.parseDouble(MyArrListx.get(i));
e = Double.parseDouble(MyArrListy.get(i));
final String phone = (MyArrListphonenumber.get(i));
map.addMarker(new MarkerOptions().position(new LatLng(n, e)) .title("Click to Call Transporter !!").snippet( phone )
.position(new LatLng(n, e)))
.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {


if (marker.getSnippet().equals(phone)) // if marker source is clicked
dialContactPhone(phone);


}
});


It calls the number of the first marker snippet only, with all the marker in time that each snippet contains a different number.

Answer

Take the call to setOnInfoWindowClickListener() out of the loop, there is only one InfoWindowClickListener for the map, and it is used for all Markers.

Then, just get the phone number from the snippet in the OnInfoWindowClickListener.

This should be sufficient for your needs:

for ( i = 0; i < MyArrListx.size(); i++) {
  n = Double.parseDouble(MyArrListx.get(i));
  e = Double.parseDouble(MyArrListy.get(i));
  String phone = (MyArrListphonenumber.get(i));
  map.addMarker(new MarkerOptions().position(new LatLng(n, e)) 
                .title("Click to Call Transporter !!").snippet( phone )
                .position(new LatLng(n, e)))
                .setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}



map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {

            //Just get the phone number stored in the snippet, and dial
            String phone = marker.getSnippet();
            dialContactPhone(phone);
        }
    });

Note, if you need to do something more complicated than just what you can store in the Title and Snippet, then use a HashMap to store your data, and use the Marker ID as the keys of the HashMap, see here for more info: http://stackoverflow.com/a/30602617/4409409