0
votes

I've built a for loop to test a set of locations and when true send lat/long values to a function to create markers. My problem is the marker moves, but doesn't make additional markers. I'm not clear on why this happens because I would think since I'm making a new instance variable every time the addMarker function is called, that I would get another marker on the map. Any help is appreciated. Thanks.

function addMarker(x, y) {
    var myLatLng = {
        lat: parseFloat(x),
        lng: parseFloat(y)
    };
    console.log(myLatLng);
    var map = new google.maps.Map(document.getElementById("map"), {
        zoom: 6,
        center: myLatLng
    });
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: 'hello world'
    });
    markers.push(marker);
    marker.setMap(map);
}
1

1 Answers

2
votes

It is because each loop you're creating a new map on this line:

var map = new google.maps.Map(document.getElementById("map"),{
  zoom: 6,
  center: myLatLng
});

you need to declare that one time, not each loop:

var neighborhoods = [
  {lat: 52.511, lng: 13.447},
  {lat: 52.549, lng: 13.422},
  {lat: 52.497, lng: 13.396},
  {lat: 52.517, lng: 13.394}
];

var markers = [];
var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: {lat: 52.520, lng: 13.410}
  });
}

function addMarkers() {
  for (var i = 0; i < neighborhoods.length; i++) {
    markers.push(new google.maps.Marker({
      position: neighborhoods[i]
      map: map,
      animation: google.maps.Animation.DROP
    }));
  }
}