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)); | |
} |
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
A great solution or https://arxiv.org/ftp/arxiv/papers/1212/1212.3193.pdf