(latlngs, crs)
| 6539 | * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polyline. |
| 6540 | */ |
| 6541 | function polylineCenter(latlngs, crs) { |
| 6542 | var i, halfDist, segDist, dist, p1, p2, ratio, center; |
| 6543 | |
| 6544 | if (!latlngs || latlngs.length === 0) { |
| 6545 | throw new Error('latlngs not passed'); |
| 6546 | } |
| 6547 | |
| 6548 | if (!isFlat(latlngs)) { |
| 6549 | console.warn('latlngs are not flat! Only the first ring will be used'); |
| 6550 | latlngs = latlngs[0]; |
| 6551 | } |
| 6552 | |
| 6553 | var centroidLatLng = toLatLng([0, 0]); |
| 6554 | |
| 6555 | var bounds = toLatLngBounds(latlngs); |
| 6556 | var areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest()); |
| 6557 | // tests showed that below 1700 rounding errors are happening |
| 6558 | if (areaBounds < 1700) { |
| 6559 | // getting a inexact center, to move the latlngs near to [0, 0] to prevent rounding errors |
| 6560 | centroidLatLng = centroid(latlngs); |
| 6561 | } |
| 6562 | |
| 6563 | var len = latlngs.length; |
| 6564 | var points = []; |
| 6565 | for (i = 0; i < len; i++) { |
| 6566 | var latlng = toLatLng(latlngs[i]); |
| 6567 | points.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng]))); |
| 6568 | } |
| 6569 | |
| 6570 | for (i = 0, halfDist = 0; i < len - 1; i++) { |
| 6571 | halfDist += points[i].distanceTo(points[i + 1]) / 2; |
| 6572 | } |
| 6573 | |
| 6574 | // The line is so small in the current view that all points are on the same pixel. |
| 6575 | if (halfDist === 0) { |
| 6576 | center = points[0]; |
| 6577 | } else { |
| 6578 | for (i = 0, dist = 0; i < len - 1; i++) { |
| 6579 | p1 = points[i]; |
| 6580 | p2 = points[i + 1]; |
| 6581 | segDist = p1.distanceTo(p2); |
| 6582 | dist += segDist; |
| 6583 | |
| 6584 | if (dist > halfDist) { |
| 6585 | ratio = (dist - halfDist) / segDist; |
| 6586 | center = [ |
| 6587 | p2.x - ratio * (p2.x - p1.x), |
| 6588 | p2.y - ratio * (p2.y - p1.y) |
| 6589 | ]; |
| 6590 | break; |
| 6591 | } |
| 6592 | } |
| 6593 | } |
| 6594 | |
| 6595 | var latlngCenter = crs.unproject(toPoint(center)); |
| 6596 | return toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]); |
| 6597 | } |
| 6598 |
no test coverage detected