(latlngs, crs)
| 6221 | * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polygon. |
| 6222 | */ |
| 6223 | function polygonCenter(latlngs, crs) { |
| 6224 | var i, j, p1, p2, f, area, x, y, center; |
| 6225 | |
| 6226 | if (!latlngs || latlngs.length === 0) { |
| 6227 | throw new Error('latlngs not passed'); |
| 6228 | } |
| 6229 | |
| 6230 | if (!isFlat(latlngs)) { |
| 6231 | console.warn('latlngs are not flat! Only the first ring will be used'); |
| 6232 | latlngs = latlngs[0]; |
| 6233 | } |
| 6234 | |
| 6235 | var centroidLatLng = toLatLng([0, 0]); |
| 6236 | |
| 6237 | var bounds = toLatLngBounds(latlngs); |
| 6238 | var areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest()); |
| 6239 | // tests showed that below 1700 rounding errors are happening |
| 6240 | if (areaBounds < 1700) { |
| 6241 | // getting a inexact center, to move the latlngs near to [0, 0] to prevent rounding errors |
| 6242 | centroidLatLng = centroid(latlngs); |
| 6243 | } |
| 6244 | |
| 6245 | var len = latlngs.length; |
| 6246 | var points = []; |
| 6247 | for (i = 0; i < len; i++) { |
| 6248 | var latlng = toLatLng(latlngs[i]); |
| 6249 | points.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng]))); |
| 6250 | } |
| 6251 | |
| 6252 | area = x = y = 0; |
| 6253 | |
| 6254 | // polygon centroid algorithm; |
| 6255 | for (i = 0, j = len - 1; i < len; j = i++) { |
| 6256 | p1 = points[i]; |
| 6257 | p2 = points[j]; |
| 6258 | |
| 6259 | f = p1.y * p2.x - p2.y * p1.x; |
| 6260 | x += (p1.x + p2.x) * f; |
| 6261 | y += (p1.y + p2.y) * f; |
| 6262 | area += f * 3; |
| 6263 | } |
| 6264 | |
| 6265 | if (area === 0) { |
| 6266 | // Polygon is so small that all points are on same pixel. |
| 6267 | center = points[0]; |
| 6268 | } else { |
| 6269 | center = [x / area, y / area]; |
| 6270 | } |
| 6271 | |
| 6272 | var latlngCenter = crs.unproject(toPoint(center)); |
| 6273 | return toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]); |
| 6274 | } |
| 6275 | |
| 6276 | /* @function centroid(latlngs: LatLng[]): LatLng |
| 6277 | * Returns the 'center of mass' of the passed LatLngs. |
no test coverage detected