我有以下代码,但它不起作用,链接只显示在最后一点(阿根廷),有些帮助吗?
<div id="map" style="width: 980px; height: 420px;margin:10px 0px 30px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var usa = new google.maps.LatLng(37.09024, -95.712891);
var brasil = new google.maps.LatLng(-14.235004, -51.92528);
var argentina = new google.maps.LatLng(-38.416097, -63.616672);
var marker = new google.maps.Marker({
position: usa,
url: '/destinos/exibir/pais_id/3',
title: 'Estados Unidos',
map: map
});
var marker = new google.maps.Marker({
position: brasil,
url: '/destinos/exibir/pais_id/2',
title: 'Brasil',
map: map
});
var marker = new google.maps.Marker({
position: argentina,
url: '/destinos/exibir/pais_id/1',
title: 'Argentina',
map: map
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
</script>
答案 0 :(得分:11)
jsfiddle演示修改了扩充@hsz示例:
问题是您已将标记声明了3次,并且仅在最后声明的标记上附加了click事件。因此,您必须为3个不同的标记声明3个不同的名称,并使用onclick事件附加每个标记。如果你在一个数组或其他东西中做得更好
var markers = [];
markers[0] = new google.maps.Marker({
position: usa,
url: '/destinos/exibir/pais_id/3',
title: 'Estados Unidos',
map: map
});
markers[1] = new google.maps.Marker({
position: brasil,
url: '/destinos/exibir/pais_id/2',
title: 'Brasil',
map: map
});
markers[2] = new google.maps.Marker({
position: argentina,
url: '/destinos/exibir/pais_id/1',
title: 'Argentina',
map: map
});
for ( i = 0; i < markers.length; i++ ) {
google.maps.event.addListener(markers[i], 'click', function() {
window.location.href = this.url; //changed from markers[i] to this
});
}
答案 1 :(得分:4)
您为每个标记赋予相同的变量名称,因此我认为引用“标记”仅指向最后一个(阿根廷)。
您可以尝试给它们单独的名称,并将侦听器分别绑定到每个名称。
答案 2 :(得分:3)
如果他们需要,只需添加此答案以供将来参考
将详细信息发送到另一个createMarker函数
createMarker(pos,title,weburl)
{
marker = new google.maps.Marker({
position: pos,
title: title,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = weburl;
});
}
感谢Tom Elliott指出这个问题,我使用的逻辑类似于kjy112