Layer Circumference Length in Leaflet.js

2019-09-09 19:30发布

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!

2条回答
该账号已被封号
2楼-- · 2019-09-09 20:00

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();
查看更多
在下西门庆
3楼-- · 2019-09-09 20:15

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.

查看更多
登录 后发表回答