Google maps - how to find a marker in a marker array?

How to check if google map marker is in marker array?
Even after that markersArray.push(marker); condition (marker in markersArray) is false.

+4
source share
4 answers

First, (marker in markersArray) is incorrect, since in does not look for elements in the array.
He is looking for properties.

The way it worked for me was

 for (var i=0; i<markersArray.length; i++) { if (markersArray[i].getPosition().equals(marker.getPosition())) { ... 

This works as long as you only need to compare marker coordinates.
We use here the .lequals operator of the LatLng class.

+5
source

You have to iterate over the array to check the marker.

 for (var i=0; i<markersArray.length; i++) { if (markersArray[i] === marker) { //doSomething... break; } } 
+2
source
 var marker = new google.maps.Marker({ icon:icon, position: position, map: map }); 

Tokens have their own identifier. You can get this id

 var marker_id = marker.__gm_id; 

and then get a marker on the map

 map.Hb.qa[marker_id]; 
0
source
 markersArray.indexOf(marker) > -1 
-1
source

All Articles