开发者

Google Maps Marker Click Event

开发者 https://www.devze.com 2022-12-23 12:25 出处:网络
I\'d like to populate a google map with several markers. When the user clicks on a marker I would like it to send the user to a different webpage which is designated for that location. (for example: l

I'd like to populate a google map with several markers. When the user clicks on a marker I would like it to send the user to a different webpage which is designated for that location. (for example: lets say the markers represent homes, when you click on a marker it takes you to a page with more information about the home)

What is th开发者_如何学运维e simplest way to do this?


I believe that as of google map v3, GEvent is not recognized, the below worked for me

google.maps.event.addListener(marker, "click", function() {
    window.location = url;
});


You will need to attach an event listener to each marker. The click handler can set document.location to the URL of the page you want to go to.

var marker = new GMarker(location);
GEvent.addListener(marker, "click", function() {
    window.location = theURL;
});
map.addOverlay(marker);

Since you will probably be adding markers in a loop, you will need to make sure each one gets its own URL. Since closures keep the actual variables they access (not their values), you probably need to put at least addListener code in its own function to create its own scope. Your loop would look kind of like this:

function createMarker(location, url) {
    var marker = new GMarker(location);
    GEvent.addListener(marker, "click", function() {
        window.location = url;
    });
    return marker;
}

// Assuming locations is an array of objects with lat, lng, and url properties
for (var i = 0; i < locations.length; i++) {
    var loc = locations[i];
    map.addOverlay(createMarker(new GLatLng(loc.lat, loc.lng), loc.url));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消