Google地图标记点击活动

Mik*_*ike 19 javascript google-maps

我想用几个标记填充谷歌地图.当用户点击标记时,我希望它将用户发送到为该位置指定的不同网页.(例如:假设标记代表家庭,当您点击标记时,它会将您带到一个页面,其中包含有关房屋的更多信息)

最简单的方法是什么?

Din*_*deh 51

我相信,截至谷歌地图v3,GEvent不被认可,下面对我有用

google.maps.event.addListener(marker, "click", function() {
    window.location = url;
});
Run Code Online (Sandbox Code Playgroud)


Mat*_*ley 21

您需要为每个标记附加一个事件监听器.点击处理程序可以设置document.location为您要转到的页面的URL.

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

由于您可能会在循环中添加标记,因此您需要确保每个标记都有自己的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));
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案的读者应该注意,如果你使用的是v3,那么需要用google.maps.event替换GEvent.高投票看看其他答案! (3认同)