Google Maps API — Unique Active Icon per marker on click

后端 未结 1 1118
我在风中等你
我在风中等你 2020-12-21 18:33

I have the following JS using the Google Maps API:

// initialize variables
var infowindow = null;
var directionDisplay;
var directionsService = new google.ma         


        
1条回答
  •  伪装坚强ぢ
    2020-12-21 19:04

    You need to change the click listener function:

        google.maps.event.addListener(marker, "click", function () {
            for (var i = 0; i < gmarkers.length; i++) {
               gmarkers[i].setIcon(defaultIcon);
            }
            this.setIcon(activeIcon);
    
            infowindow.setContent(this.html);
            infowindow.open(map, this);
        });
    

    You need to save the "unique" icon for each marker and change it back to that one, rather than the defaultIcon. Simplest would probably be to save it as a property of the marker (i.e. marker.myDefaultIcon), then you can do something like this:

    gmarkers[i].setIcon(gmarkers[i].myDefaultIcon);
    

    jsfiddle (again modified from your previous question)

    UPDATE: I get a javascript error on the link you provided:

    Error: marker[i] is undefined
    Source File: http://zslabs.com/jhtwp/wp-content/plugins/busipress/js/map.1349993292.js
    Line: 105
    

    105 is this line: this.setIcon(marker[i].myActiveIcon);

    here:

        google.maps.event.addListener(marker, "click", function () {
            for (var i = 0; i < gmarkers.length; i++) {
               gmarkers[i].setIcon(gmarkers[i].myDefaultIcon);
            }
            this.setIcon(marker[i].myActiveIcon);
    
            infowindow.setContent(this.html);
            infowindow.open(map, this);
        });
    

    I think you want this.myActiveIcon.

    jsfiddle illustrating the concept ("dots" are active, no dot is default)

    0 讨论(0)
提交回复
热议问题