How to access Google Maps markers after creating them dynamically?

I am creating markers for multiple points like this:

for (i = 0; i < locations.length; i++) {

  console.log("Adding marker...");

  marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map,
            draggable:true,
            icon: locations[i][3]
  });

  google.maps.event.addListener(marker, 'dragend', function(){

      console.log(marker.getPosition());
      // This doesn't work :(
  });

}

I then want to (with getPosition) access the positions (lat & long) of each marker when they are moved. How would I achieve that? There will most likely always be 2 markers on the map, so I would need to access marker 0 and marker 1 and log each of them when they are moved.

UPDATE 1:

I tried adding id: locations[i][0] to the marker and then accessing it with: console.log(marker.id); But that always returns the ID/name of the second marker, even if the first one is moved.

Answers 1

  • You store the markers into an array while creating them

    var arr_marker=[];
    for (i = 0; i < locations.length; i++) {
    
      console.log("Adding marker...");
    
      marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                map: map,
                draggable:true,
                icon: locations[i][3]
      });
    
      google.maps.event.addListener(marker, 'dragend', function(){
    
          console.log(marker.getPosition());
          // This doesn't work :(
      });
    arr_marker[] = marker;
    }


Related Articles