问题
Any idea how to get the Circumference length of the shapes in a layer in MapBox/Leaflet.js? I managed to get the area using this example (even though it is sometimes negative!?). It does not have circumference/perimeter though.
Thanks!
回答1:
For L.Circle you can calculate the circumference from it's radius:
L.Circle.include({
circumference: function () {
return 2 * Math.PI * this.getRadius();
}
});
var circle = new L.Circle(...),
circumference = circle.circumference();
For L.Polyline you'll need to sum the distances between the L.LatLng objects:
L.Polyline.include({
length: function () {
var latlngs = this.getLatLngs();
var length = 0;
for (var i = 0, n = latlngs.length - 1; i< n; i++) {
length += latlngs[i].distanceTo(latlngs[i+1]);
}
return length;
}
});
var polyline = new L.Polyline(...),
length = polyline.length();
For L.Polygon which is extended from L.Polyline you call the length function of L.Polyline and add the distance between the first and last L.LatLng objects:
L.Polygon.include({
circumference: function () {
var length = L.Polyline.prototype.length.call(this);
var latlngs = this.getLatLngs();
if (latlngs.length > 2) {
length += latlngs[0].distanceTo(latlngs[latlngs.length - 1]);
}
return length;
}
});
var polygon = new L.Polygon(...),
circumference = polygon.circumference();
回答2:
Thanks for the answers and comments. Seems like turf.js is the way to go, as suggested by @ghybs. It still requires some coding for anything that's not a LineString, but at least the algorithms are efficient.
来源:https://stackoverflow.com/questions/33939754/layer-circumference-length-in-leaflet-js