javascript Google Maps API v3,单击时如何更改标记图标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6319188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Maps API v3, how to change marker icon when clicked
提问by wzazza
How can I change a marker icon when a marker is clicked (on a click event) and return it back to a normal icon when another marker is clicked?
如何在单击标记时(在单击事件中)更改标记图标并在单击另一个标记时将其恢复为正常图标?
回答by bobfet1
Just in any case anyone wants to see an example of keeping track of the previous marker in a global variable like Kasper mentioned, here is what I did:
无论如何,任何人都希望看到一个在像 Kasper 提到的全局变量中跟踪前一个标记的示例,这就是我所做的:
google.maps.event.addListener(marker,'click',function() {
if (selectedMarker) {
selectedMarker.setIcon(normalIcon);
}
marker.setIcon(selectedIcon);
selectedMarker = marker;
});
(after setting selectedMarker as a global variable)
(将 selectedMarker 设置为全局变量后)
回答by Trott
I haven't tested this code, so there may be a typos or bugs, but it should give you the idea.
我还没有测试过这段代码,所以可能有错别字或错误,但它应该给你一个想法。
First, define a callback to set all markers to the normal icon (to reset any previously clicked markers) and set the current clicked marker's icon to the selected icon:
首先,定义一个回调以将所有标记设置为普通图标(以重置任何先前单击的标记)并将当前单击的标记的图标设置为选定的图标:
var markerCallback = function() {
for (var i=0; i<arrayOfMarkers.length; i++) {
arrayOfMarkers[i].setIcon(normalIcon);
}
this.setIcon(selectedIcon);
}
Then, assign the callback to the click event on each marker like so:
然后,将回调分配给每个标记上的点击事件,如下所示:
google.maps.event.addListener(marker, 'click', markerCallback);
There are certainly some code improvements that could be made. For example, you might not want normalIcon
, selectedIcon
, and arrayOfMarkers
to be global variables the way the code above assumes they are. And if you have a lot of markers, you probably want to instead keep track of the previously selected marker rather than having a for
loop reset the icon on every one of them.
当然可以进行一些代码改进。例如,您可能不希望normalIcon
,selectedIcon
和arrayOfMarkers
成为上面代码假定的全局变量。如果您有很多标记,您可能想要跟踪先前选择的标记,而不是让for
循环重置每个标记上的图标。
But like I said, this should give you the idea.
但就像我说的,这应该给你这个想法。