首页 > 解决方案 > 当您有多个标记时,更改单击的标记图标

问题描述

我试图在单击标记时更改标记图标问题是下面的代码仅更改我添加到地图的最后一个标记而不是我单击的标记,因此如果我只有一个标记它会正常工作。我尝试查找它,但我能找到的所有示例仅适用于地图中加载的 1 个标记。我尝试了两种不同的侦听器方式,第二种方式在第一种方式下方被注释掉,两者都只是更改最后加载的标记的图标。

<html>

  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 95%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 95%;
        margin: 0;
        padding: 0;
      }
 
    <script src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap"
        async defer></script>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script src="https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js"></script>
    <script>
    let markers = [];
    let map;

    function loadMarkers(ssStr)
    {
        $.getJSON(ssStr, function(data) {
        for (var i = 0; i < data.feed.entry.length; i++)
        {
        var latLng = new google.maps.LatLng(data.feed.entry[i]['gsx$lat']['$t'], 
            data.feed.entry[i]['gsx$long']['$t']);

        var marker = new google.maps.Marker({
            position:  latLng,
            map: map,
            label:data.feed.entry[i]['gsx$structure']['$t'],
            icon: {      url: "http://maps.google.com/mapfiles/ms/icons/red.png"          }
            });
            
        markers.push(marker);   
        google.maps.event.addListener(marker, 'click', function() {
            //Change the marker icon
            marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green.png');
            }); 

    /*  marker.addListener("click", (event) => {
        marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green.png');
        }); */
        }   
        var latLng = new google.maps.LatLng(data.feed.entry[0]['gsx$lat']['$t'], 
            data.feed.entry[0]['gsx$long']['$t']);
        map.setCenter(latLng);

        }); 
    }

    function initMap() {
        console.log("initMap");
        var mapOptions = {
            zoom: 10,
            center: new google.maps.LatLng(41.5, -72)
        };
        map = new google.maps.Map(document.getElementById('map'), mapOptions);  
        
        loadMarkers("http://spreadsheets.google.com/feeds/list/SSID/od6/public/values?alt=json");

    }

  </script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>

标签: javascriptgoogle-maps

解决方案


推荐阅读