Home > front end >  get difference of previous and current cursor in js loop
get difference of previous and current cursor in js loop

Time:06-22

I have an array with x elements given lat - lng value. My aim is to find the distance difference between the previous position and the next position in the loop as long as the number of elements (length) of the array with the haversine formula.

Example my array value;

var array = [
    [51.06745252933975, -114.11267548799515],
    [51.067506465746014, -114.09559518098831],
    [51.0827140244322,-114.0949085354805],
    [51.088267312195484,-114.10709649324417]];

I don't have a problem with math, my goal is to get the cursor in the loop as the previous element vs. the next actually pointer order.

Sketchy code recipe;

1st index of the loop; array[0] lat-lng and array[1] lat-lng calc distance

2nd index of the loop; array[1] lat-lng and array[2] lat-lng calc distance

I'm using Javascript and how do I do it most ideally?

CodePudding user response:

Seems a bit easy, but I might be not understand the question at all, if the question is how to loop an array by comparing to the previous entry, there are several ways to do it, one way could be shown below

// https://stackoverflow.com/a/27943/28004
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2)  
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}
// end of pasted code

// your entry
const points = [
    [51.06745252933975, -114.11267548799515],
    [51.067506465746014, -114.09559518098831],
    [51.0827140244322,-114.0949085354805],
    [51.088267312195484,-114.10709649324417]
]

// looping through all points starting from the second element
for (let i = 1; i < points.length; i  = 1) {
  const lastPosition = points[i-1];
  const newPosition = points[i];
  console.log(
      `from position ${i-1} to ${i} it's %s Km`,
      getDistanceFromLatLonInKm(lastPosition[0], lastPosition[1], newPosition[0], newPosition[1]))
}

Keep in mind that there's no validation (1 entry only will through an error) and that the Haversine formula only calculates a straight line between 2 points and does to take into account that the planet is not a sphere.

  • Related