Google Maps - How to locate a marker in a markers array?
How can I check if a google map marker is already inside an array of markers?
Even after thismarkersArray.push(marker);
the condition (marker in 开发者_如何学PythonmarkersArray)
is false.First, (marker in markersArray)
is wrong since in
doesn't look for elements in the array.
It looks 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 what you need compared is only the coordinates of the markers.
We use here the LatLng class' .equals operator.
You should iterate through the array to check for the marker.
for (var i=0; i<markersArray.length; i++) {
if (markersArray[i] === marker) {
//doSomething...
break;
}
}
var marker = new google.maps.Marker({
icon:icon,
position: position,
map: map
});
Markers have own ID. You can get this ID by
var marker_id = marker.__gm_id;
and then get marker on map
map.Hb.qa[marker_id];
markersArray.indexOf(marker) > -1
精彩评论