Javascript 谷歌地图标记点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2489483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Maps Marker Click Event
提问by Mike
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 the simplest way to do this?
什么是最简单的方法来做到这一点?
回答by DinoSaadeh
I believe that as of google map v3, GEvent is not recognized, the below worked for me
我相信从谷歌地图 v3 开始,GEvent 无法识别,以下对我有用
google.maps.event.addListener(marker, "click", function() {
window.location = url;
});
回答by Matthew Crumley
You will need to attach an event listener to each marker. The click handler can set document.locationto the URL of the page you want to go to.
您需要为每个标记附加一个事件侦听器。单击处理程序可以设置document.location为您要访问的页面的 URL。
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 addListenercode in its own function to create its own scope. Your loop would look kind of like this:
由于您可能会在循环中添加标记,因此您需要确保每个标记都有自己的 URL。由于闭包保留了它们访问的实际变量(而不是它们的值),因此您可能至少需要addListener在其自己的函数中放置代码来创建自己的作用域。你的循环看起来像这样:
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));
}

