[GIS] How to get leaflet polyline segment length

geojsonleafletlinelinestring

I'm working on a project that plots out some pipes on a leaflet map, these are displayed on the map as polylines with arrows showing flow direction.

i am feeding the data in as geojson linestrings via ajax.

each "pipe" has multiple segments and i am calculating the approx total length of all segments server side and putting it in as a property of the linestring. this all works fine. the problem is, i also need the length of each segment.

i am having no luck figuring out how to get the start and end of each segment of a polyline in leaflet, if i could get the start and end coordinates i could use the haversine formula to work out the approx length.

if i cant figure this out i will have to make 1 linestring for each segment, and will loose the ability to calculate the total length server side as well as make my geojson file HUGE as it will have to store the properties for each segment of a line, not a big issue if it has only 2-3 segments, but if it has 20,30,100 or more segments it will be huge.

Best Answer

You could be interested in Leaflet measurement plugins, e.g. Leaflet Measure Path (demo):

A plugin to show measurements on paths (polylines, polygons and circles currently supported).

Otherwise, you can very easily do it yourself, using these methods:

https://plnkr.co/edit/kFbRkrM9p2J9AYVLHe3R?p=preview

polyline.getLatLngs().forEach(function (latLng) {
  if (previousPoint) {
    L.marker(latLng).bindPopup(
      'Distance from previous point: '
      + previousPoint.distanceTo(latLng)
      + ' meter(s)'
    ).addTo(map);
  }
  previousPoint = latLng;
});
Related Question