Skip to content

Instantly share code, notes, and snippets.

@jeremejazz
Last active February 22, 2021 21:19
Show Gist options
  • Save jeremejazz/9407568 to your computer and use it in GitHub Desktop.
Save jeremejazz/9407568 to your computer and use it in GitHub Desktop.
Return Center polygon in google maps v3. This does not apply to some shapes though. I recommend using turf.js instead https://turfjs.org/
function polygonCenter(poly) {
var lowx,
highx,
lowy,
highy,
lats = [],
lngs = [],
vertices = poly.getPath();
for(var i=0; i<vertices.length; i++) {
lngs.push(vertices.getAt(i).lng());
lats.push(vertices.getAt(i).lat());
}
lats.sort();
lngs.sort();
lowx = lats[0];
highx = lats[vertices.length - 1];
lowy = lngs[0];
highy = lngs[vertices.length - 1];
center_x = lowx + ((highx-lowx) / 2);
center_y = lowy + ((highy - lowy) / 2);
return (new google.maps.LatLng(center_x, center_y));
}
@ErliSoares
Copy link

ErliSoares commented Jan 1, 2020

@oriionis
Copy link

it works fine! thanks!

@jeremejazz
Copy link
Author

That's great. You can also check this function turf.centerOfMass or centroid
https://turfjs.org/docs/#centerOfMass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment