javascriptjquery-mobilegoogle-maps-api-3google-maps-markers

Google Maps Marker Can't Be Removed


I'm having a problem with my markers in a Google Maps web-app. I can add markers, but I can't remove them. I have been looking for several days for a solution but the standard advice for v3 seems to be:

marker.setMap(null);

The problem is that this seems to be completely ineffective in my code. Here is a sample of a function ran on start-up. It gets the current location quickly at low accuracy. A later function which takes longer to complete should then remove the marker and place a new marker in the more accurate location. Problem is, I cannot remove the marker once placed.

function geoLocCheckAndFastLatLng(){


    if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition(function(position) {

               //get current position
                pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

                //place low accuracy marker

                placeMarker(pos,window.meIconMediumAccuracy,window.myPositionMarker);

                //and center map

                 window.map.setCenter(pos);

                 window.map.setZoom(14);

                 window.myPositionMarker.setMap(null);

                 });

    }else{

        alert("Sorry - You're Browser Doesn't Support Geolocation.\nChange To Google-Chrome Or Dolphin To Use This App");
    }

}

So the above function in theory gets the location, places a marker then removes that same marker. But the marker persists! Can anybody help? I've only got a couple of days to finish and I can't understand where I'm going wrong.

Here is the place marker function:

function placeMarker(location, iconType, marker) {

    //alert(window.markers.length);

    //if the marker is undefined it means it needs to be created form scratch
    //using the iconType and location provided in the function call
    if(marker === undefined){

    marker = new google.maps.Marker(

       {
           position: location,
           map: window.map,
           icon: iconType,
       });

    //and add a click listener
    google.maps.event.addListener(marker, 'click', function()
      {

        alert("Marker location:\n" + pos);

      });

    //add to markers array
    window.markers.push(marker);


    }else{

        marker.setPosition(location);

    }

}

Solution

  • I think the root cause of your problem is you're not actually addressing the object you think you are with the .setMap(null) call.

    Try returning your marker from placeMarker() and then assign it to a var and call the setMap(null) on that.

    If you declare window.myPositionMarker = marker after you initialize the google.maps.marker() it will work as expected.