Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google maps v3 setMap undefined when trying to clear all markers

I have seen may people here explain this function:

// REMOVE All MARKERS FUNCTION
    // Removes all markers currently on map
    // PARAMS: None
    function removeAllMarkers(){// removes all markers from map
        if (markersArray) {
            for (i in markersArray) {
                markersArray[i].setMap(null);
                markersArray = [];
                markersInfoArray = [];
            };
        };
    };

but i get a javascript error...

Break on Error markersArray[i].setMap is not a function

The page is at: http://www.focus-on-plants.com/locator.php

any ideas???

<---------------Update--------------------->

i tried the sugestions and also moved the MarkersArray=[] and markersInfoArray = [] to out side of the for loop so i had this:

for( var i = 0; i < markersArray.length; i++ ){
    markersArray[i].setMap(null);
}

But i get the same error markersArray[i].setMap is not a function

so i looked around and tried this method:

function removeAllMarkers(){// removes all markers from map
    alert('REMOVE MARKERS - markersArray count:'+ markersArray.length);
    while(markersArray[0]){
        markersArray.pop().setMap(null);
        markersInfoArray.pop()
    }
    markersArray.length = 0;
    markersInfoArray.length = 0;
};

and i still get the same error, what gives? its almost as though the setMap() does not exist, i read in another thread here that it change from set_map to setMap() but those dont work for me either :(

like image 602
Dizzy Bryan High Avatar asked Dec 05 '22 00:12

Dizzy Bryan High


2 Answers

I was having the same issue as you. But changing the for-in loop to an actual loop (as suggested here, fixed it.

There was no need to create a new google.maps.marker when removing the marker.

Sample code:


var markersArray = [];

function addMarker() { var marker = new google.maps.Marker({ position: latlng, map: map }); markersArray.push(marker); }

function removeMarker() { if (markersArray) { for (i=0; i < markersArray.length; i++) { markersArray[i].setMap(null); } markersArray.length = 0; } }

like image 191
Yaz Avatar answered May 21 '23 19:05

Yaz


Try an actual loop. for (i in markersArray) will also retrieve properties. It's not the same as, say, PHP's foreach.

for( var i = 0; i < markersArray.length; i++ ) {}
like image 25
theazureshadow Avatar answered May 21 '23 18:05

theazureshadow