Layer Circumference Length in Leaflet.js

怎甘沉沦 提交于 2019-12-13 21:07:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!