Leaflet – How to Get Total Length of a Polyline Using Leaflet Draw

leafletleaflet-drawlengthline

I'm quite new when it comes to Leaflet and this is my very first question asked here so I'm not experienced. While I was drawing polyline I noticed that you can get current distance while drawing it:
enter image description here
But I was wondering is there any method in Leaflet.Draw which can get the total distance of a created polyline so I can use it later?
Edit: As suggested this is the only code I have for now which is a basic map with some plugins:

var center = [42.6194, 25.3930];

var map = L.map('map', {
    fullscreenControl: true, fullscreenControlOptions: {
        position: 'topleft'
    },
    visualClick: true,
    visualClickPane: 'shadowPane'
}).setView(center, 7);


L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> | &copy; <a href="https://opentopomap.org/about">OpenTopoMap</a> | &copy; <a href="/">Trails</a>'
}).addTo(map);

var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);

var drawPluginOptions = {
    position: 'topleft',
    draw: {
        polyline: {
            shapeOptions: {
                color: '#c700ac',
                weight: 4
            }
        },
        polygon: false,
        circle: false,
        rectangle: false,
        circlemarker: false,
        marker: false
    },
    edit: {
        featureGroup: editableLayers,
        remove: false
    }
};

var drawControl = new L.Control.Draw(drawPluginOptions);
map.addControl(drawControl);

L.control.mousePosition().addTo(map);
L.control.scale().addTo(map);

var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);

map.on('draw:created', function (e) {
    editableLayers.addLayer(e.layer);
});

Best Answer

It seems that neither Leaflet nor Leaflet.Draw has some method to get line length, so you'll have to calculate it yourselves.

One way to do it is to use line layer .getLatLngs() method to get all line coordinates, and then loop through them and get line segments lengths (in meters) with Leaflet coordinate .distanceTo method.

Code could then look something like this:

map.on('draw:created', function (e) {
  var layer = e.layer;
  editableLayers.addLayer(layer);
  if (e.layerType = 'polyline') {
    var coords = layer.getLatLngs();
    var length = 0;
    for (var i = 0; i < coords.length - 1; i++) {
      length += coords[i].distanceTo(coords[i + 1]);
    }
    console.log(length);
  }
});