Skip to content Skip to sidebar Skip to footer

Google Maps Marker Data

I'm currently making an ajax call to the server to get a list of lat/longs to be displayed on a google map. I've attached a 'click' event to each marker as well. The trick is tha

Solution 1:

HA! I figured it out. "this" did it!

google.maps.event.addListener(newmarker, "click", function(mark) {
    alert(this.hotspotid);
});  

Solution 2:

I think your approach is right, it's just the event handler that's incorrect. In your handler

function(mark) {
    alert(mark.hotspotid);
}

The mark argument is not a marker, as you expect, but a MouseEvent (see the API reference for details).

In order to fix this, you need to use a closure to pass in the reference to the marker. This is complicated by the loop - you can't just use a reference to newmarker, as it will only ever refer to the last marker in the loop. There are a few different ways to fix this, but the easiest is to attach the click event in a separate function:

success: function (data, status, xhttp) {
    // define a function to attach the click eventfunctionattachClickEvent(marker) {
        google.maps.event.addListener(marker, "click", function() {
            // the reference to the marker will be saved in the closurealert(marker.hotspotid);
        });
    }
    for (var i = 0; i < data.length; i++) {
        var loc = new google.maps.LatLng(data[i].Lat, data[i].Long);
        var newmarker = new google.maps.Marker({
            position: loc,
            draggable: false,
            map: map,
            title: data[i].Name
        });

        newmarker.hotspotid = data[i].ID;
        attachClickEvent(newmarker);
    }
},

Post a Comment for "Google Maps Marker Data"