Reputation: 1433
Hello everyone I am new dealing with google map API , and I have a list of LatLng object that added marker on map .
for (LatLng location : camerasLocations) {
googleMap.addMarker(new MarkerOptions()
.position(location).icon(icon)
.title(cameraList.get(j).getName()));
}
I want to know the position of the marker on that array when I click on the marker with :
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
showDialog(getActivity(), "");
return false;
}
});
any help please ...
Upvotes: 1
Views: 3280
Reputation: 574
First you need to set position as tag on marker while adding marker in google map
for(int i = 0, i < camerasLocations.size(), i++){
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(location).icon(icon)
.title(cameraList.get(j).getName()))
.setTag(i);
}
And then you can obtain this marker position in the onclick method using getTag() method :
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(this, "Marker position >> " + marker.getTag(), Toast.LENGTH_SHORT).show();
return false;
}
});
Upvotes: 1
Reputation: 328
As far as I know, they are not positioned in that way. You would have to handle it yourself. If you are sure you just want to get the index based on the order of creation, you can do sth like that:
Create private field with Map, for storing that information
//class field
private Map<Marker, Integer> markersOrderNumbers = new HashMap<>();
Afterward, populate it
//Your method
int markerIndex = 0;
for (LatLng location : camerasLocations) {
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(location).icon(icon)
.title(cameraList.get(j).getName()));
markersOrderNumbers.put(marker,markerIndex);
markerIndex++;
}
And then you can obtain this index number in the onclick method
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
Integer index = markersOrderNumbers.get(marker);
//Do whatever you want to
showDialog(getActivity(), "");
return false;
}
});
I might add that if you are not certainly focused on the index itself but rather on some information that you get using that Id, you can use provided method to map marker with needed information at the first place like:
Map<Marker, Whatever> ...
Upvotes: 0