向 google.map 标记添加 onclick 事件 [英] Adding an onclick event to google.map marker

查看:69
本文介绍了向 google.map 标记添加 onclick 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图弄清楚一点点 JS :( 我有一个谷歌地图

I'm stuck trying to figure out a little bit of JS :( I have a google map

var myCenter=new google.maps.LatLng(53, -1.33);

function initialize()
{
var mapProp = {
    center:myCenter,
    zoom: 14,
    draggable: false,
    scrollwheel: false,
    mapTypeId:google.maps.MapTypeId.ROADMAP
};

var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);

var marker=new google.maps.Marker({
    position:myCenter,
    icon:'images/pin.png',
    url: 'http://www.google.com/',
    animation:google.maps.Animation.DROP
});
marker.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);

但我似乎无法为标记网址连接 onclick 事件?

But I can't seem to hook up the onclick event for the marker url?

我知道这与添加有关

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

但是我把它放在哪里都会导致地图不显示或标记不显示.

But where ever I put it causes the map to not display or the marker to not display.

推荐答案

确保 marker 是在 initialize() 之外定义的.否则,如果您尝试在 initialize() 之外分配点击侦听器,它将是 undefined.

Make sure the marker is defined outside of initialize(). Otherwise, it will be undefined if you attempt to assign the click listener outside of initialize().

此外,如果您尝试加载 url www.google.com,您可能会遇到 SAME-ORIGIN 问题,但它应该适用于本地 url.

Also, you may have SAME-ORIGIN issues if you attempt to load url www.google.com, but it should work fine with a local url.

更新代码

var myCenter=new google.maps.LatLng(53, -1.33);

var marker=new google.maps.Marker({
    position:myCenter,
    url: '/',
    animation:google.maps.Animation.DROP
});

function initialize()
{
var mapProp = {
    center:myCenter,
    zoom: 14,
    draggable: false,
    scrollwheel: false,
    mapTypeId:google.maps.MapTypeId.ROADMAP
};

var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);

marker.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(marker, 'click', function() {window.location.href = marker.url;});

Bootply 上的工作演示

这篇关于向 google.map 标记添加 onclick 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆