点击链接时动态更改谷歌地图标记文本



我尝试了很多方法在单击链接时更改标记中的标签文本,但没有找到位置。 我有以下代码:

var map = new google.maps.Map(document.getElementById('googleMap'), {
center: {lat: 51.5078788, lng: -0.0877321},
zoom: 16,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});

然后,我创建自定义标记:

var icons = {
main: {
icon: 'marker.png'
},
locationone: {
icon: 'marker-1.png'
},
locationtwo: {
icon: 'marker-2.png'
}
};

并设置功能:

var features = [
{
position: new google.maps.LatLng(51.5078788, -0.0877321),
type: 'main'
}, {
position: new google.maps.LatLng(51.5078788, -0.0877321),
type: 'locationone',
textone: 'default text',
textwo: 'onclick replace with this text',
texthree: 'onclick replace with this text'
}, {
position: new google.maps.LatLng(51.5078788, -0.0877321),
type: 'locationtwo',
textone: 'default text',
textwo: 'onclick replace with this text',
texthree: 'onclick replace with this text'
}
};

然后我在地图上绘制它们:

var marker;
var i;
for (i = 0; i < features.length; i++) {
marker = new google.maps.Marker({
position: features[i].position,
icon: icons[features[i].type].icon,
map: map,
label: { color: '#ffffff', fontWeight: 'bold', fontSize: '14px', text: String(features[i].textone) }
});
};

我有三个链接:

<a href="#">Show the label for textone</a>
<a href="#">Show the label for textwo</a>
<a href="#">Show the label for texthree</a>

当我单击上述链接之一时,我希望它替换标签文本。 这可能吗? 我该怎么做?

12个小时后,我找到了解决方案。 我希望这对其他人有所帮助。使用 onclick 事件,传递标记和功能,但将代码放在返回函数中,否则无论您是否单击它,事件都将触发。 将下面的代码放在标记函数下的 for 循环中:

$(".class-on-ahref").click(function(marker, i){
return function() {
var label = marker.getLabel();
label.text = String(features[i].textwo);
marker.setLabel(label); 
}
}(marker, i));

为每个链接创建一个 onclick 事件。

最新更新