[GIS] Calculate length of Multilinestrings/Linestrings/Polygons in geoJSON file

geojsonleafletlengthlinestringMeasurements

I have a couple of routes on my map where I would like to display the length of each route. I think I've found what I was looking for here: https://github.com/tyrasd/geojson-length, but I'm not sure how to apply the calculations.

I've tried to refer to the files I've downloaded with:

<script src="js/measureLengthGeoJSON.js"></script> 

but then I get this error message:

Uncaught ReferenceError: module is not defined
    at measureLengthGeoJSON.js:1

Line 1 refers to: module.exports.

I then tried to copy the entire formula/function like so:

var lengthGeo = function(geometry) {
    if (geometry.type === 'LineString')
        return calculateLength(geometry.coordinates);
    else if (geometry.type === 'MultiLineString')
        return geometry.coordinates.reduce(function(memo, coordinates) {
            return memo + calculateLength(coordinates);
        }, 0);
    else
        return null;
}

function calculateLength(lineString) {
    if (lineString.length<2)
        return 0;
    var result = 0;
    for (var i=1; i<lineString.length; i++)
        result += distance(lineString[i-1][0],lineString[i-1][1],
                           lineString[i  ][0],lineString[i  ][1]);
    return result;
}

/**
 * Calculate the approximate distance between two coordinates (lat/lon)
 *
 * © Chris Veness, MIT-licensed,
 * http://www.movable-type.co.uk/scripts/latlong.html#equirectangular
 */
function distance(λ1,φ1,λ2,φ2) {
    var R = 6371000;
    Δλ = (λ2 - λ1) * Math.PI / 180;
    φ1 = φ1 * Math.PI / 180;
    φ2 = φ2 * Math.PI / 180;
    var x = Δλ * Math.cos((φ1+φ2)/2);
    var y = (φ2-φ1);
    var d = Math.sqrt(x*x + y*y);
    return R * d;
};

and apply the function like so:

var testlength = lengthGeo(HvenKort);

console.log(testlength);

Nothing is outputted to the console. I can't figure out what I'm doing wrong.

Any suggestion on how to fix it or any other library that is capable of calculation distances of Multilinestrings/Linestrings/Polygons?

Best Answer

Make sure that you're applying lengthGeo to the feature's geometry, not the Leaflet layer. Say my_leaflet_line is your Leaflet polyline layer, you should do lengthGeo(my_leaflet_line.feature.geometry), not lengthGeo(my_leaflet_line).

my_leaflet_line.feature.geometry is where the original GeoJSON coordinates are stored, and that's what lengthGeo is built to operate on.

Related Question