【问题标题】:Google Maps setIcon to update path (not URL)谷歌地图 setIcon 更新路径(不是 URL)
【发布时间】:2019-06-12 20:31:47
【问题描述】:

我似乎找不到任何有关在 Google Maps API 中更新图标(标记)路径的文档。在这个特定示例中,我尝试将图标的 fillOpacity 从 0 更改为 1。

var myIcon = {
  path: google.maps.SymbolPath.CIRCLE,
  scale: 5,
  fillColor: "#ff00ff",
  fillOpacity: 0,
  strokeColor: "#ff00ff",
  strokeWeight: 2
};

var marker = new google.maps.Marker({
  position: position,
  icon: myIcon,
  map: map,
  title: 'My Marker>' 
});

marker.addListener('click', function() {
  this.setOptions({icon:{fillOpacity: 0.5}}); // Not working
  this.setIcon({fillOpacity: 0.2}); // Not working either
});

【问题讨论】:

    标签: google-maps-api-3 path icons


    【解决方案1】:

    “图标”是一个匿名对象。您需要重新设置整个对象:

    marker.addListener('click', function() {
      myIcon.fillOpacity = 0.5;
      this.setIcon(myIcon);
    });
    

    或:

    marker.addListener('click', function() {
      myIcon.fillOpacity = 0.5;
      this.setOptions({
        icon: myIcon
      }); 
    });
    

    proof of concept fiddle

    代码 sn-p:

    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        center: {
          lat: -25.363882,
          lng: 131.044922
        }
      });
      var myIcon = {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 5,
        fillColor: "#ff00ff",
        fillOpacity: 0,
        strokeColor: "#ff00ff",
        strokeWeight: 2
      };
    
      var marker = new google.maps.Marker({
        position: map.getCenter(),
        icon: myIcon,
        map: map,
        title: 'My Marker>'
      });
    
      marker.addListener('click', function() {
        myIcon.fillOpacity = 0.5;
        this.setIcon(myIcon);
      });
    }
    html,
    body,
    #map {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <div id="map"></div>
    <!-- Replace the value of the key parameter with your own API key. -->
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

    【讨论】:

    • 非常感谢您的快速而有价值的回答,这解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 2015-03-24
    相关资源
    最近更新 更多