简体   繁体   中英

Google map in javascript: Some markers don't have click event

I have a problem when working with marker in Google map. A list of places that needs to appear on map, I create a loop for a all of them, every marker, I set a click event. But many (not all) markers don't have click event, I can't event click on them. Some markers still work. I don't know why, please help me, thanks so much. Here is my code.

// Store all markers
gMakers = [];

for (var key in places) {
  (function(key) {
    var location = {lat: Number(places[key].ln.lat), lng: Number(places[key].ln.lon)};
    var marker = new google.maps.Marker({position: location, map: map});

    marker.addListener('click', function() {
        alert('clicked');
    });
    gMakers.push(marker);
  })(key);
}

Try using this

// Store all markers
gMakers = [];
    for (var key in places) {
  (function(key) {
    var location = {lat: Number(places[key].ln.lat), lng: Number(places[key].ln.lon)};
    var marker = new google.maps.Marker({position: location, map: map});

    google.maps.event.addListener(marker, "click", function() {
    alert('clicked');
  });
    gMakers.push(marker);
  })(key);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM