2

Problem with the following code is that the click event is not fired. The markers appear on the map as expected, but when clicked, nothing appears in the console. I've been searching for a while now, but all the answers I find are not relevant to my code.

/*
* Connect to Google API, load map and markers
*/
function drawMarkers(markerInfo) {
    var mapOptions = {
        center: { lat: 50.601079, lng: 4.4764595},
        zoom: 8,
        scrollwheel: false,
        styles: style
    };

    var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

    for (var i = 0; i < markerInfo.length; i++) {
        var Latlng = new google.maps.LatLng(markerInfo[i][0],markerInfo[i][1]);
        var title = markerInfo[i][2];

        var marker = new google.maps.Marker({
            position: Latlng,
            animation: google.maps.Animation.DROP,
            map: map,               
            title:title,
            icon: markerUrl
        });
    };

    google.maps.event.addListener(marker, 'click', function() {
        console.log('test');        
    });

};

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

I've got no idea what the problem could be, because there are no errors, and I can't seem to find the problem...

EDIT: When I refresh the page and I zoom out, so a marker which wasn't visible yet get's loaded in, only that one responds to the click event.

user3165926
  • 93
  • 3
  • 9

2 Answers2

3

You only add the listener to the last marker, attach the listener in the loop and you'll be attaching the event to each marker.

for (var i = 0; i < markerInfo.length; i++) {
    var Latlng = new google.maps.LatLng(markerInfo[i][0],markerInfo[i][1]);
    var title = markerInfo[i][2];

    var marker = new google.maps.Marker({
        position: Latlng,
        animation: google.maps.Animation.DROP,
        map: map,               
        title:title,
        icon: markerUrl
    });
    google.maps.event.addListener(marker, 'click', function() {
        console.log('test');        
    });
};
Musa
  • 96,336
  • 17
  • 118
  • 137
0

You should probably create a function , which accepts marker as the argument , and call the function from within the for loop itself passing the current marker as the parameter.

function addListner(marker)
{
 google.maps.event.addListener(marker, 'click', function() {
    console.log('test');        
});
}

And call the function inside the loop.

While referring to marker outside the for loop there is no reference to which marker it referring to. You need to assign a listener to each marker individually.

pratiklodha
  • 1,095
  • 12
  • 20