点击即可更改Google地图标记符号颜色

时间:2017-07-11 20:57:51

标签: google-maps svg google-maps-markers

我正在为地图标记ala使用自定义SVG符号:https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom

我似乎无法找到有关如何更改任何这些SVG选项的任何文档,以创建“激活的”#39;单击时标记。我想更改自定义符号的颜色或比例。

我能找到的最接近的例子是:

marker.setIcon("_URL-GOES-HERE_");

但是,这是特定于自定义图标图像 - 而不是自定义符号。这可能吗?

1 个答案:

答案 0 :(得分:1)

单击图标时,可以通过使用新颜色创建图标版本来更改单击颜色:

marker.addListener('click', changeColor);

function changeColor(evt) {
  this.setIcon(pinSymbol('blue'));
}

function pinSymbol(color) {
    return {
        path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
        fillColor: color,
        fillOpacity: 1,
        strokeColor: '#000',
        strokeWeight: 2,
        scale: 1
    };
}

proof of concept fiddle

代码段



var markers = [];

function initialize() {
  var latlng = new google.maps.LatLng(47.605, -122.333);
  var myOptions = {
    zoom: 10,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  var marker = createMarker(latlng, 'red', map);
  var marker1 = createMarker(new google.maps.LatLng(47.5, -122.0), 'green', map);
  var marker2 = createMarker(new google.maps.LatLng(47.6, -122.2), 'orange', map);
  var marker3 = createMarker(new google.maps.LatLng(47.7, -122.1), 'yellow', map);
}

function createMarker(position, color, map) {
  var marker = new google.maps.Marker({
    map: map,
    position: position,
    icon: pinSymbol(color),
    originalColor: color
  });
  marker.addListener('click', changeColor);
  markers.push(marker);
  return marker;
}

function changeColor(evt) {
  restoreColors();
  this.setIcon(pinSymbol('blue'));
}

function pinSymbol(color) {
  return {
    path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
    fillColor: color,
    fillOpacity: 1,
    strokeColor: '#000',
    strokeWeight: 2,
    scale: 1
  };
}

function restoreColors() {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setIcon(pinSymbol(markers[i].originalColor));
  }
}
google.maps.event.addDomListener(window, 'load', initialize);
&#13;
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
&#13;
&#13;
&#13;