Skip to content

Instantly share code, notes, and snippets.

@stevedev
Created June 6, 2014 23:03
Show Gist options
  • Save stevedev/a08fd663fc9390f0b12f to your computer and use it in GitHub Desktop.
Save stevedev/a08fd663fc9390f0b12f to your computer and use it in GitHub Desktop.
Get centroid for polygon in Google Maps
google.maps.Polygon::getArea = ->
points = @getPaths()
area = 0
i = 0
j = points.length - 1
while i < points.length
point1 = points[i]
point2 = points[j]
area += point1.lng() * point2.lat()
area -= point1.lat() * point2.lng()
j = i
i++
area /= 2
area
google.maps.Polygon::getCentroid = ->
points = @getPaths()
x = 0
y = 0
i = 0
j = points.length - 1
while i < points.length
point1 = points[i]
point2 = points[j]
f = point1.lng() * point2.lat() - point2.lng() * point1.lat()
x += (point1.lng() + point2.lng()) * f
y += (point1.lat() + point2.lat()) * f
j = i
i++
f = @getArea() * 6
new google.maps.LatLng(x / f, y / f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment