Leaflet.js中的层周长

问题描述:

有人知道如何在MapBox/Leaflet.js的图层中获取形状的周长吗?我设法使用此示例(即使有时是负面的!?).它没有周长/周长.

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.

谢谢!

对于L.Circle,您可以根据其半径计算周长:

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();

对于L.Polyline,您需要对L.LatLng个对象之间的距离求和:

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();

对于从L.Polyline扩展的L.Polygon,您调用L.Polyline的长度函数,并添加第一个和最后一个L.LatLng对象之间的距离:

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();