简体   繁体   English

Google地图标记点击活动

[英]Google Maps Marker Click Event

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? 最简单的方法是什么?

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;
});

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. 单击处理程序可以将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. 由于您可能会在循环中添加标记,因此您需要确保每个标记都有自己的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. 由于闭包保持它们访问的实际变量(而不是它们的值),因此您可能需要在其自己的函数中至少放置addListener代码以创建自己的作用域。 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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM