Search code examples
javascriptgoogle-mapskmlgoogle-earth

How can I get the distance between two lat lng coordinates based on a kml route?


I have a kml file exported from Google Earth which is essentially a path of part of the River Thames in London. I have put this into Google Maps with Javascript as a KmlLayer.

I need to find a way to calculate the distance between one point on the route and the end of the route. Obviously it can't just be linear distance as the route goes up, down, back, forth etc.

I can't think of a way to do this using a kml file and Google Maps so any other suggestions or methods would be fine. I could perhaps gather the coordinates from the kml file and using them another way on the map? But I'm not sure where to start.

Apologies as always if this question has been answered elsewhere, but I have looked and had no luck.

Thanks in advance,

Adam

the route, generated in google earth


Solution

  • I found a solution, and that was to extract the kml coordinates into a javascript array of objects.

    I then iterated through the array and got the distance between each point on the route using the Haversine Formula, and assigned each object a distance value (from the start of the route).

    From there I could work out at each point on the route, how far it was from the start and finish just by using the distance value.

    views.string = '-1.692525715111287,51.692324976351,0 -1.691353785046965,51.69214295521361,0 -1.690097310611129,51.69205100316109,0...//etc etc';
    
        var array = views.string.split(',0 ');
    
        map.route = [];
    
        $.each(array, function (i, e) {
            if ((i + 1) == array.length) {
                e = e.replace(',0', '');
            }
            var coords = e.split(',');
            map.route.push({ lat: parseFloat(coords[1]), lng: parseFloat(coords[0]) });
        });
    
        var distance = 0;
        $.each(map.route, function (i, e) {
            if (map.route[i - 1] != undefined) {
                var d = map.getDistance(map.route[i - 1], e);
                distance += d;
                e.distance = distance;
            }
            else {
                e.distance = distance;
            }
        });