-
-
Save jeremejazz/9407568 to your computer and use it in GitHub Desktop.
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)); | |
} |
Works great! Just defined center_x and center_y on top to make it work
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();
Excellent job, it works beautifully. Thanks.
Doesn't work when the polygon is a triangle:
http://jsfiddle.net/fn3nbvuy/290/?utm_source=website&utm_medium=embed&utm_campaign=fn3nbvuy
great it! Thanks.
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. 😄 🗺️
it works fine! thanks!
That's great. You can also check this function turf.centerOfMass or centroid
https://turfjs.org/docs/#centerOfMass
Works like a charm ! thanks ;)