How to calculate the distance of a polyline in Leaflet like geojson.io?

后端 未结 4 1819
日久生厌
日久生厌 2021-02-15 03:04

I am working on a map with Mapbox and Leaflet and I am supposed to let the user draw polygons and calculate and show the are of that polygon and I also need to let the user draw

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-15 03:35

    I solved this by extending L.Polyline class, and using LatLng's distanceTo method:

    L.Polyline = L.Polyline.include({
        getDistance: function(system) {
            // distance in meters
            var mDistanse = 0,
                length = this._latlngs.length;
            for (var i = 1; i < length; i++) {
                mDistanse += this._latlngs[i].distanceTo(this._latlngs[i - 1]);
            }
            // optional
            if (system === 'imperial') {
                return mDistanse / 1609.34;
            } else {
                return mDistanse / 1000;
            }
        }
    });
    

    Hope it helps someone.

提交回复
热议问题