1

Is there a way to calculate the travelled distance in Mapbox?

For example: if a user clicks the start button it'll record the travelled path and calculate the distance. I know it's possible to calculate a distance between two geopoints described here, however a user can go off-road and therefore won't choose to walk the fastest/most suited route between two geopoints. I would like to sum ALL walked kilometers.

Monitor position

navigator.geolocation.watchPosition(function(position) {
  document.getElementById('distance').innerHTML =
      calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
                        position.coords.latitude, position.coords.longitude);
});

Calculate distance

function calculateDistance(lat1, lon1, lat2, lon2) {
  var R = 6371; // km
  var dLat = (lat2 - lat1).toRad();
  var dLon = (lon2 - lon1).toRad(); 
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
          Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
          Math.sin(dLon / 2) * Math.sin(dLon / 2); 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); 
  var d = R * c;
  return d;
}
Number.prototype.toRad = function() {
  return this * Math.PI / 180;
}

EDIT: one possible solution could be that every time I get a new location I calculate distance between previous geopoint and new geopoint and use that to calculate distance. If I want to see total distance I sum all the distances between previous points. I can also use that data to plot a line between all stored geopoints. Does this makes sense? Is there a more efficient way to do this since this is a pure javascript solution (maybe there is a more related to Mapbox solution?)

Rover
  • 387
  • 4
  • 14

0 Answers0