Google Maps Api 3 Remove Selected Marker Only

Working Sample on jsFiddle


Google Maps doesn't manage your markers. So all your markers should be managed by yourself.

Make a global marker object and push all markers to this object. And give unique id to each marker when getting a marker instance. Then when you want to delete a marker take its id and find this marker in global marker object and finally call this marker instance's setMap method with passing null argument.

Also I've added a demo that works on jsFiddle. Code is heavily documented.

Your psuedo code should be like this. For more detailed code please look the demo.

var currentId = 0;
var uniqueId = function() {
    return ++currentId;
}

var markers = {};
var createMarker = function() {
    var id = uniqueId(); // get new id
    var marker = new google.maps.Marker({ // create a marker and set id
        id: id,
        position: Gpoint,
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP
    });
    markers[id] = marker; // cache created marker to markers object with id as its key
    return marker;
}
var deleteMarker = function(id) {
    var marker = markers[id]; // find the marker by given id
    marker.setMap(null);
}

Just pass your marker in the rightclick function. For example:

var marker = new google.maps.Marker({
    position: event.latLng,
    map: map,
    draggable: true,
    title: 'Hello World!'
});
google.maps.event.addListener(marker, "rightclick", function (point) {delMarker(marker)});

And make the function look this:

var delMarker = function (markerPar) {
    markerPar.setMap(null);
}

Your markers will be removeable on the rightclicks.


this worked for me:

a second currentId, if you have a better idea, let me know

var actualMarkerId = 0;
var currentId = 0;



    if (actualMarkerId>0) {
        deleteMarker(actualMarkerId);
        console.log(actualMarkerId);
    }
    var id = uniqueId(); // get new id
    actualMarkerId = id;

Complementing the @Fatih answer you should manage the markers. For example you could add each marker in a array and then to remove, you could find this marker into the array and set the val in the map null.