SimonBarker
SimonBarker

Reputation: 1424

Deleting google maps markers when stored in object

I want to populate a Google Map with markers from locations stored in a database and then allow the user to delete any of the markers by double clicking the marker to be removed. Using the code below populates the map but when any of the markers are double clicked the last marker is removed.

I assume this is happening because the double click event listener is being reassigned each time to the current marker but I can't work out how to stop this happening.

I have a jsFiddle set up here http://jsfiddle.net/simonbarker/TA4HP/

var markers = {"locations": [{"name" : "UK 1", "date" : "Nov 1", "lat" : 51, "lng" : 0.164},
                               {"name" : "France 1", "date" : "Nov 2", "lat" : 50, "lng" : 0.164},
                               {"name" : "France 2", "date" : "Nov 2", "lat" : 49, "lng" : 0.164}]
                };

  var map;
  var center = new google.maps.LatLng(markers.locations[1].lat,markers.locations[1].lng);

  var mapOptions = {
    zoom: 8,
    center: center,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  createMarkers();


  //create markers by traversing throught the markers object
  function createMarkers(){

    var i = 0;
    while(markers.locations[i]){

      var marker = new google.maps.Marker({
          position: new google.maps.LatLng(markers.locations[i].lat, markers.locations[i].lng),
          animation: google.maps.Animation.DROP,
          map: map
      });

      //store marker in the locations object
      markers.locations[i].marker = marker;

      //add delete handler
      google.maps.event.addListener(marker, 'dblclick', function(event) {
        marker.setMap(null);
        delete markers.locations[i];
      });

      i++;

    }
  }​

Any help would be great

UPDATE:

I solved this by changing the delete handler function to

//add delete handler
          google.maps.event.addListener(marker, 'dblclick', function(event) {
            this.setMap(null);
            delete markers.locations[this.id];
          });

and adding an id to the marker when creating it

var marker = new google.maps.Marker({
              id: i, 
              position: new google.maps.LatLng(markers.locations[i].lat, markers.locations[i].lng),
              animation: google.maps.Animation.DROP,
              map: map
          });

Upvotes: 0

Views: 1984

Answers (2)

Marcelo
Marcelo

Reputation: 9407

You need to create your markers in a separate function to obtain closure

Same answer as this

Explanation here.

Upvotes: 1

Matt Olan
Matt Olan

Reputation: 1959

Store the objects in an array or dict so that you can reference them later with this line to remove them...

map.removeOverlay(marker);

Upvotes: 0

Related Questions