Google Maps Api - Deleting marker with mouseclick
I got a problem with deleting a marker on mouse click. Well, the thing isnt as simple as it seems.
function addPoint(event) {
path.insertAt(path.length, event.latLng);
var marker = new google.maps.Marker({
position: event.latLng,
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
marker.setMap(null);
markers.splice(i, 1);
}
);
If i used that code, adding listener right away when creating marker, deleting it would be easy, cuz i refer to marker.setMap(null);
. But in my case i want them to be created, and then i want to add the event listener to them using
function usun(){
for (var i=0; i<markersArray.length; i++){
google.maps.event.addListener(marker, 'click', function() {
alert('lol');
});
}
I am pushing each marker to markersArray
which lets me to add event to each of it now, but how can i delete it? When i put marker.setMap(null);
in place of the alert, it says marker is not defined, and i dunno how can i refer to marker i just clicked :S
also cant use marker as global variable, cuz i am getting Uncaught TypeError: Cannot read property '__e3_' of undefined
error.
EDIT: if i try using
function usun(){
for (var i=0; i<markersArray.length; i++){
开发者_JAVA技巧google.maps.event.addListener(markersArray[i], 'click', function() {
markersArray[i].setMap(null);
});
}
}
i get the error Uncaught TypeError: Cannot call method 'setMap' of undefined
. Thats why i was sure i need to use "marker".
In your for loop you are not referring to the marker that is in the array.
try this:
function usun(){
for (var i=0; i < markersArray.length; i++){
google.maps.event.addListener(markersArray[i], 'click', function() {
this.setMap(null);
});
}
working example: http://jsfiddle.net/52nJc/1/
精彩评论