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));
}
@aaroncrawford
Copy link

Yes, for this to work, just modify the var declarations at the top to read :

var lowx, highx, lowy, highy, lats = [], lngs = [], center_x, center_y, vertices = poly.getPath();

@Sparker73
Copy link

Excellent job, it works beautifully. Thanks.

@sky93
Copy link

sky93 commented Oct 17, 2018

@kenjiKashiwabara
Copy link

great it! Thanks.

@jeremejazz
Copy link
Author

jeremejazz commented Nov 21, 2019

Hi guys, This was written a while ago just to solve a simple problem. I am surprised this is being used.
Though you might want to use turf.js instead for your map related operations. It can be easily used with Google maps or any JS map libraries. 😄 🗺️

@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