将谷歌地图标记颜色更改为我选择的颜色

时间:2016-10-27 16:16:46

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

无论如何,从默认的红色标记颜色变为我选择的十六进制颜色?我一直在寻找堆栈溢出,我似乎找不到答案。这是我到目前为止所做的。

var marker = new google.maps.Marker({
            position: myLatLng,
            label: '23',
            map: map
        });

2 个答案:

答案 0 :(得分:4)

一种选择是为标记图标定义SVG符号。可以在构造函数中设置SVG图标颜色。

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
    };
}

然后像这样使用它:

var marker1 = new google.maps.Marker({
  map: map,
  position: new google.maps.LatLng(47.5, -122.0),
  icon: pinSymbol('green')
});

enter image description here

proof of concept fiddle

代码段

function initialize() {
  var latlng = new google.maps.LatLng(47.605, -122.2);
  var myOptions = {
    zoom: 10,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"),
    myOptions);
  var marker = new google.maps.Marker({
    map: map,
    position: latlng,
    icon: pinSymbol('red')
  });

  var marker1 = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(47.5, -122.0),
    icon: pinSymbol('#7CFC00')
  });
  var marker2 = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(47.6, -122.3),
    icon: pinSymbol('orange')
  });
  var marker3 = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(47.7, -122.1),
    icon: pinSymbol('yellow')
  });
}

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
  };
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>

答案 1 :(得分:0)

标记没有颜色属性/属性..标记使用图标,因此您可以更改颜色更改图标

这是来自google-maps dev

var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var beachMarker = new google.maps.Marker({
   position: {lat: -33.890, lng: 151.274},
   map: map,
   icon: image
 });