Search code examples
javascriptgoogle-mapsgoogle-maps-api-2

Map not adding click event handlers to markers


The code below will add markers to my map. But the add Listener event never gets added to each marker.

    var mapDiv = document.getElementById("google-map");
    var infowindow = new google.maps.InfoWindow({
        content: 'test'
    });

    var map = new google.maps.Map(mapDiv);
    map.setCenter(new GLatLng(53.635784, 6.943359));
    map.setZoom(5);

    for (var i = 0; i < data.length; i++) {
        var dataMarker = data[i];
        var marker = new GLatLng(dataMarker.Latitude, dataMarker.Longitude);
        map.addOverlay(new google.maps.Marker(marker, {
            title: dataMarker.Name,
            html: dataMarker.HtmlAttributes[0]
        }));
        google.maps.event.addListener(marker, 'click', function () {                
            infoWindow.setContent(this.html);
            infoWindow.open(map, this);
        });            
    }

What am I doing wrong?

Oh and I am using Maps v2.


Solution

  • You did not add any listener to marker.

    var marker = new GLatLng(dataMarker.Latitude, dataMarker.Longitude);
    

    marker is not a google.maps.Marker , it's a google.maps.LatLng , which will not respond to mouse-events, because it's not an UI-element, it's just a javascript-object