Google Maps Api 3 Remove Selected Marker Only
Asked Answered
U

6

23

I've 2 function as below:

function addMarker() {
    marker = new google.maps.Marker({
        position: Gpoint,
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP
    });
    map.panTo(Gpoint);

    google.maps.event.addListener(marker, "rightclick", 
    function (point) { 
    showContextMarker(point.latLng); } ); 
    $('.contextmenu').remove();
};

function delMarker() { marker.setMap(null); $('.contextmenu').remove(); };

So, as may understand I have a Context Menu having "Delete Marker" option on it. I am binding a "rightclick" listener during adding a marker, to show this menu.

Everything is working without any problem till this moment.

But when I try to click on a marker to delete; it is effecting only the last added marker. When I try again; nothing happens.

So my idea is to get the clicked marker's id (or something that may well be useful) and run this deleting function according to this.

Briefly; I want to delete the marker that I clicked on, from a map having multiple markers.

Do you have any approach to solve this problem ?

Thanks in advance!

SOLVED!

Here is the solution. Thank you Fatih. it was impossible without your guidance:

var id;
var markers = {};
var addMarker = function () {
    marker = new google.maps.Marker({ 
        position: Gpoint,
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP
    });
    map.panTo(Gpoint);
    id = marker.__gm_id
    markers[id] = marker; 

    google.maps.event.addListener(marker, "rightclick", function (point) { id = this.__gm_id; delMarker(id) });
}

var delMarker = function (id) {
    marker = markers[id]; 
    marker.setMap(null);
}

Calling delete function by: delMarker(id) Ps: "Right clicking is enough on this case"

Thank you!

Untouchability answered 15/12, 2011 at 14:37 Comment(5)
But what do you want to achieve???. Remove all the markers?Sapir
Remove only the one that clicked on!Injunction
@MrGorki,how did you generate the __gm_id?is that incremented?Timbering
@Timbering it is being given by google maps api itself. it is an auto generate number. But you can generate your own id like a guid or index number etc. and use it as marker idInjunction
Seems that __gm_id is no longer a value returned from Marker... need to generate a random one insteadCamlet
D
49

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);
}
Demurral answered 15/12, 2011 at 14:49 Comment(8)
I thought same but couldn't figure out how. How can I get the id of an instance by clicking on the map to compare with my array?Injunction
"marker.__gm_id" seems the id but how can I trace it? by getElementbyId or something else? Any help will be really appreciated!Injunction
First of all, I shouldn't offer you use an array because when you use array, you must search the marker in array. There is no need to this while using an object instead of array. The second one is that you can take the id property of the marker when you right click the marker, I guess you know which marker you clicked. If you know it then just use .id to get it. If you don't know implement a way to achieve that. So the logic is like this.Demurral
I got the logic and it seems really nice but how can I find the id that you defined by clicking? var marker = markers[id]; // find the marker by given id. Please excuse me but I couldn't understand why we assigned another id. and even if we assigned; how can we find this id from the marker it self? I am really sorry :(Injunction
Check working sample. I've just choose to use lat + '_' + lng as markerId.Demurral
@Fatih,where did you find the keyword delete in google map API?.I have no idea where did you get that keyword delete.please enligthen my mindTimbering
@jemz, I have no idea right now, it was an answer added 3 years ago. I don't look Google Maps API for years. All I can suggest you right now is, some Google APIs don't document all methods you need to look which methods are owned by your object in DevTools or Firebug. Here is an example from SO page. take.ms/OF4yHDemurral
@Faith, Hi I have only recently come across this as I am having trouble doing something similar. I am wanting to do a few things with the markers on the map. 1) Create a list with all the markers. 2) On selecting a marker with the right-click event, having the ability to change its color, direction, etc. [Only to a select few markers]. Here is my jsFiddle. I am wondering if you could help me out! jsfiddle.net/holdentorana74/bwuowf2y/11Ampoule
S
2

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.

Sapir answered 15/12, 2011 at 14:55 Comment(0)
R
2

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.

Retorsion answered 1/11, 2016 at 15:9 Comment(0)
G
1

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;
Giffin answered 24/8, 2013 at 15:16 Comment(0)
I
0

For minimal changes

var newid=0;

for (var index in results){

var marker = new google.maps.Marker({

map: map,
icon: image,

__gm_id: = newid+1,

});
}

Now marker['__gm_id'] still has a value

Idealistic answered 23/7, 2014 at 15:34 Comment(0)
G
0

Simple,Use Global array for marker Objects. Push marker object in that array on plotting marker. Yes,We can use Id in Marker Object for Unique Reference.

Code As Below

MarkerArray = []

marker = new google.maps.Marker({
         Id: 1,
         position: new google.maps.LatLng(Lat,Long),
         type: 'info'         
          });

MarkerArray.push(marker);

To remove particular Marker,Find that Element Index using Unique Id for Each Marker.

var MarkerIndex = MarkerArray.findIndex(function GetIndex(element) {
            return element.Id == 1;
});    
MarkerArray[MarkerIndex].setMap(null);
MarkerArray.splice(MarkerIndex, 1); // to remove element from global array
Given answered 4/7, 2019 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.