Google Maps setIcon更新路径(不是URL)

时间:2019-01-18 14:47:17

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

我似乎找不到任何有关更新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
});

1 个答案:

答案 0 :(得分:0)

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

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

screenshot of map after clicking marker

代码段:

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>