google.maps.Circle类

时间:2016-07-20 09:14:30

标签: google-maps-api-3

google.maps.Circle类中没有任何getPath()函数。如何使用getRadius()和getCenter()函数获得近似路径?

1 个答案:

答案 0 :(得分:3)

您可以使用google.maps.geometry.spherical.computeOffset方法计算具有相同半径和中心的圆形多边形的路径(需要geometry库)。

function circlePath(circle) {
  var numPts = 512;
  var path = [];
  for (var i = 0; i < numPts; i++) {
    path.push(google.maps.geometry.spherical.computeOffset(circle.getCenter(), circle.getRadius(), i * 360 / numPts));
  }
  return path;
}

代码段

var geocoder;
var map;

function circlePath(circle) {
  var numPts = 512;
  var path = [];
  for (var i = 0; i < numPts; i++) {
    path.push(google.maps.geometry.spherical.computeOffset(circle.getCenter(), circle.getRadius(), i * 360 / numPts));
  }
  return path;
}

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var circle = new google.maps.Circle({
    map: map,
    radius: 1000,
    center: map.getCenter(),
    fillOpacity: 0.2
  });
  var polygon = new google.maps.Polygon({
    map: map,
    paths: [circlePath(circle)],
    fillColor: 'red',
    fillOpacity: 0.5,
    strokeColor: 'red'
  });
  google.maps.event.addDomListener(document.getElementById('circle'), 'click', function() {
    circle.setMap(circle.getMap() == null ? map : null);
  });
  google.maps.event.addDomListener(document.getElementById('polygon'), 'click', function() {
    polygon.setMap(polygon.getMap() == null ? map : null);
  });
}
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?libraries=geometry"></script>
<input type="button" id="circle" value="toggle circle" />
<input type="button" id="polygon" value="toggle polygon" />

<div id="map_canvas"></div>