简体   繁体   English

Google Maps API v3,单击时如何更改标记图标

[英]Google Maps API v3, how to change marker icon when clicked

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?如何在单击标记时(在单击事件上)更改标记图标,并在单击另一个标记时将其恢复为正常图标?

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 设置为全局变量后)

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.例如,您可能不希望normalIconselectedIconarrayOfMarkers成为上面代码假定的全局变量。 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.如果您有很多标记,您可能希望跟踪先前选择的标记,而不是让for循环重置每个标记上的图标。

But like I said, this should give you the idea.但就像我说的,这应该给你的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM