Google Map - 更改现有标记的样式属性并更新地图

时间:2016-12-21 11:17:44

标签: javascript google-maps google-maps-api-3

在Google地图中,可以创建地图并放置自定义标记,如下所示

let lat = 19.29;
let long = 72.85;
let map = new google.maps.Map(document.getElementById('map'), {zoom: 12});
let LatLng = new google.maps.LatLng(lat, long);
let marker = new google.maps.Marker({
                    position: LatLng,
                    map: map,
                    icon: { path: google.maps.SymbolPath.CIRCLE,
                            scale: 2,
                            fillColor: 'Crimson',
                            strokeColor: 'Crimson'                          
                          }
                });

我们如何更改标记样式,例如fillColor

这个问题与标记为副本的问题不同 - 这个问题是关于更新现有标记的样式属性以及特定于谷歌地图api v3的通用。

1 个答案:

答案 0 :(得分:2)

从标记中获取当前图标,更改其颜色,设置新图标:

var icon = marker.getIcon();
icon.fillColor = "#00FF00";
icon.strokeColor = "#00FF00";
marker.setIcon(icon);

proof of concept fiddle

代码段

var color = ["#FF0000", "#00FF00", "#0000FF"];
var colorIdx = 1;

function initialize() {

  let lat = 19.29;
  let long = 72.85;
  let LatLng = new google.maps.LatLng(lat, long);
  let map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: LatLng
  });
  let marker = new google.maps.Marker({
    position: LatLng,
    map: map,
    icon: {
      path: google.maps.SymbolPath.CIRCLE,
      scale: 10,
      fillColor: 'Crimson',
      strokeColor: 'Crimson'
    }
  });
  google.maps.event.addDomListener(document.getElementById('btn'), 'click', function() {
    var icon = marker.getIcon();
    icon.fillColor = color[colorIdx];
    icon.strokeColor = color[colorIdx];
    colorIdx++;
    colorIdx %= color.length;
    marker.setIcon(icon);
  })
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input type="button" id="btn" value="change color" />
<div id="map"></div>