Last active
February 22, 2021 21:19
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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();