Menztrual
Menztrual

Reputation: 41607

Google Maps overlay wont position over correct markers

I'm trying to make a list of markers to pin onto a map, each having its own overlay. It's mostly working, however the overlays are all being positioned over the top of one another instead of its corresponding marker.

Code is as follows:

var myCenter = getMyLocation();

function initialize()
{
  var mapProp = {
    center: myCenter,
    zoom:9,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);

  var locations = [
    {lat: -27.646670, lng: 152.86918630, text: 'Address #1'},
    {lat: -27.6446550, lng: 152.7822390, text: 'Address #2'},
    {lat: -27.6062480, lng: 152.7889550, text: 'Address #3'}
  ];

  // Loop through our list and plot them on the map
  locations.forEach(function (l) {

    marker =  new google.maps.Marker({
      position: new google.maps.LatLng(l.lat, l.lng),
    });

    marker.setMap(map);

    // Create our infoWindow panel for our marker
    var infoWindow = new google.maps.InfoWindow({
      content: l.text
    });

    // Bind click event for our marker
    google.maps.event.addListener(marker, 'click', function () {
      infoWindow.open(map, marker);
    });
  });

}

google.maps.event.addDomListener(window, 'load', initialize);

I have a feeling that the issue is something to do with the on click addListener event

Upvotes: 1

Views: 229

Answers (2)

Michael Geary
Michael Geary

Reputation: 28880

You're simply missing a var:

marker =  new google.maps.Marker(...

should be:

var marker =  new google.maps.Marker(

As a result, you only have a single global marker variable instead of a unique one for each marker as you should.

Since you're using .forEach with a callback function, that callback function provides you with a closure for each iteration of the loop. So all you need is to take advantage of that closure by making marker a local variable inside the callback.

Upvotes: 3

Aleko
Aleko

Reputation: 970

Maybe closure will help you? Marker is an object, because of it on every loop link to it changes. Closure will prevent it.

google.maps.event.addListener(marker, 'click', (function(marker){ return function () {
      infoWindow.open(map, marker);
};})(marker));

Upvotes: 0

Related Questions