在Google地图中为变量创建样式

时间:2018-01-06 23:30:03

标签: javascript google-maps

我有这个代码在地图中包含一个点但是我想知道,我可以创建一个样式来包含fillColor和fillOpacity吗?而不是每次我创建一个新的var时使用它?我会在地图上创建几个点:)!这就是为什么我要问它

    var circle = new google.maps.Circle({
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 0,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    map: map,
    center: {lat: 41.7141904, lng: -87.643531},
    radius: 50
    });

1 个答案:

答案 0 :(得分:1)

编写一个函数来创建一个具有所需固定参数的圆,然后调用它。

function createCircle(options) {
  var circle = new google.maps.Circle(options);
  circle.setOptions({
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  return circle;
}

proof of concept fiddle

screenshot of resulting map

代码段

function createCircle(options) {
  var circle = new google.maps.Circle(options);
  circle.setOptions({
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  return circle;
}

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(41.7141904, -87.643531),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var circle1 = createCircle({
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 0,
    map: map,
    center: {
      lat: 41.7141904,
      lng: -87.643531
    },
    radius: 50
  });
  var circle2 = createCircle({
    strokeColor: '#0000FF',
    strokeOpacity: 0.8,
    strokeWeight: 1,
    map: map,
    center: {
      lat: 41.71,
      lng: -87.643
    },
    radius: 100
  });
  var circle3 = createCircle({
    strokeColor: '#FF00FF',
    strokeOpacity: 1.0,
    strokeWeight: 2,
    map: map,
    center: {
      lat: 41.718,
      lng: -87.6425
    },
    radius: 150
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>