'getPath function in google.maps.Circle class

There is no any getPath() function in the google.maps.Circle class. How can I get an approximated path using the getRadius() and getCenter() funcions?



Solution 1:[1]

You can use the google.maps.geometry.spherical.computeOffset method to calculate a path for a circular polygon with the same radius and center (requires the geometry library).

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

code snippet:

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&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" id="circle" value="toggle circle" />
<input type="button" id="polygon" value="toggle polygon" />

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1