Skip to content

Instantly share code, notes, and snippets.

@mashbridge
Last active December 27, 2015 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mashbridge/7331812 to your computer and use it in GitHub Desktop.
Save mashbridge/7331812 to your computer and use it in GitHub Desktop.
Using the Google Maps API v3 to draw a circle of given radius around a point.
// Given c as google.maps.LatLng, r in meters.
function drawCircle(c, r) {
var cLat = c.lat() * Math.PI / 180;
var cLng = c.lng() * Math.PI / 180;
var d = r / 6378137.0;
var paths = [];
// http://williams.best.vwh.net/avform.htm#LL
// Using 64 segments.
for (var tc = 0; tc < 2 * Math.PI; tc += (Math.PI / 32)) {
var lat = Math.asin(Math.sin(cLat) * Math.cos(d)
+ Math.cos(cLat) * Math.sin(d) * Math.cos(tc));
var dlng = Math.atan2(Math.sin(tc) * Math.sin(d) * Math.cos(cLat),
Math.cos(d) - Math.sin(cLat) * Math.sin(lat));
var lng = ((cLng - dlng + Math.PI) % (2 * Math.PI)) - Math.PI;
paths.push(new google.maps.LatLng(toDeg(lat), toDeg(lng)));
}
var opts = {
paths: paths,
fillColor: '#53575A',
draggable: true,
geodesic: true,
map: map,
strokeWeight: 0
};
return new google.maps.Polygon(opts);
}
function toDeg(r) { return r * 180 / Math.PI; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment