gpt4 book ai didi

javascript - 悬停标记图标在谷歌地图上发生变化

转载 作者:行者123 更新时间:2023-11-30 15:54:44 26 4
gpt4 key购买 nike

我看到他们已经提出了几个这样的问题,根据这些答案又提出了一个新问题,

我已经在 map 上显示了多个标记,现在我需要如果我将鼠标悬停到特定标记然后更改图标,当我将光标从标记上移开然后设置上一个图标时,下面是我的代码

for (i = 0; i < Object.size(locations); i++) { 
marker = new google.maps.Marker({
position : new google.maps.LatLng(locations[i][1], locations[i][2]),
icon : site_url+'/assets/front/images/'+locations[i][4],
map : map,
url : site_url+'/detail/'+locations[i][3],
draggable: false,
hovericon: site_url+'/assets/front/images/'+hovericon,
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
google.maps.event.addListener(marker, "mouseover", function() {
marker.setIcon(this.hovericon);
});
google.maps.event.addListener(marker, "mouseout", function() {
marker.setIcon(this.icon);
});
markers.push(marker);

function AutoCenter() {
var bounds = new google.maps.LatLngBounds();
$.each(markers, function (index, marker) {
bounds.extend(marker.position);
});
map.fitBounds(bounds);
}
AutoCenter();
}

上面的代码显示了多个标记,这很好,但是当我将鼠标悬停在特定标记上时,它总是会更改最后一个标记图标,但我只需要更改图标,而不是最后一个。

enter image description here

如果我将鼠标悬停在任何标记上,总是最后一个图标会发生变化,请参见附图如果我将鼠标悬停在第一个上,则倒数第二个图标会发生变化。

我做错了什么,有什么帮助吗?

最佳答案

发生这种情况是因为当 for 结束时,您将最后一个要更改的标记附加到监听器。

您可以在 addListeners 中使用这个 insetead of marker 来获得预期的。

for (i = 0; i < Object.size(locations); i++) { 
marker = new google.maps.Marker({
position : new google.maps.LatLng(locations[i][1], locations[i][2]),
icon : site_url+'/assets/front/images/'+locations[i][4],
map : map,
url : site_url+'/detail/'+locations[i][3],
draggable: false,
originalicon: site_url+'/assets/front/images/'+locations[i][4],
hovericon: site_url+'/assets/front/images/'+hovericon
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
google.maps.event.addListener(marker, "mouseover", function() {
this.setIcon(this.hovericon);
});
google.maps.event.addListener(marker, "mouseout", function() {
//you have to retreive the original icon cause with the mouse hover you change the marker icon attribute
this.setIcon(this.originalicon);
});
markers.push(marker);

function AutoCenter() {
var bounds = new google.maps.LatLngBounds();
$.each(markers, function (index, marker) {
bounds.extend(marker.position);
});
map.fitBounds(bounds);
}
AutoCenter();
}

通过这种方式,您可以引用正在与之交互的元素(鼠标悬停和鼠标移出),而不是 for 循环中的最后一个元素。

我没有测试代码,所以我不确定是否有效。

this工作样本的 fiddle

希望对你有帮助

关于javascript - 悬停标记图标在谷歌地图上发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38762970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com