Reputation:
I need to convert a google maps Circle into GeoJSON. GeoJSON doesn't support circles so I want to generate an N-sided polygon. I found a nice method for generating a regular N-sided polygon but that requires the radius to be defined in the coordinate system while the radius of a circle in Google Maps is defined in meters.
Upvotes: 5
Views: 5684
Reputation:
Google Maps has a handy set of spherical functions in the geometry library that makes this really easy for us. Specifically, we want the computeOffset
function:
Returns the LatLng resulting from moving a distance from an origin in the specified heading (expressed in degrees clockwise from north).
We have the origin (the center of the circle) and a distance (the radius of the circle), so we just need to calculate a set of headings for the points based on how many sides we want.
function generateGeoJSONCircle(center, radius, numSides){
var points = [],
degreeStep = 360 / numSides;
for(var i = 0; i < numSides; i++){
var gpos = google.maps.geometry.spherical.computeOffset(center, radius, degreeStep * i);
points.push([gpos.lng(), gpos.lat()]);
};
// Duplicate the last point to close the geojson ring
points.push(points[0]);
return {
type: 'Polygon',
coordinates: [ points ]
};
}
The geometry library is not included by default. You must specifically ask for it via the libraries parameter.
Upvotes: 17