Question

I have a gpx file. I'm displaying it on top of OSM using OpenLayers and this example.

My requirement is to get distance of the route. How can i achieve that?

Please help, Thanks.

Was it helpful?

Solution

Basically, A GPX is an XML file defining a set of Track Segment which holds a list of Track Points which are logically connected in order.

<trkseg>
     <trkpt lat='float' lon='float'/>
     <trkpt lat='float' lon='float'/>
     <trkpt lat='float' lon='float'/>
...
</trkseg> 

All you need is to compute All the track segment length using distance from point to point (the points hold the lat and lon) The distance from point to point will be compute using the following formula :

var radius = 6378137.0 ; // earth radius in meter
var DE2RA = 0.01745329252; // degre to radian conversion

// return the distance between (lat1,lon1) and (lat2,lon2) in meter.
GCDistance= function (lat1, lon1, lat2, lon2) {
    if (lat1 == lat2 && lon1 == lon2) return 0;
    lat1 *= DE2RA;
    lon1 *= DE2RA;
    lat2 *= DE2RA;
    lon2 *= DE2RA;
    var d = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2);
    return (radius * Math.acos(d));
};

Be aware of the fact that Track Segment are NOT logically connected.

Parsing the GPX using DOM is straight forward.

this code is extract from a lib which in use for years. here a sample of where I use it.

Hope this help. G.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top