-2

I need a tool to measure distance beetween a fixed point and my location. I used this code to calculate the distance and created the part that takes coordinates from browser. Get distance () returns NaN. What's wrong?

<p id="demo"></p>
<script>
  var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
  };
  navigator.geolocation.getCurrentPosition(success, error, options);

  function success(pos) {
    var lat1 = pos.coords.latitude;
    var lon1 = pos.coords.longitude;
    var lat2 = 50; //Sample target latitude
    var lon2 = 20; //Sample target longitude
  }

  function error(err) {
    document.getElementById('demo').textContent = "Error.";
  }

  //haversine formula

  function getDistance(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)
  }

  function final(getDistance, success, lat1, lon1, lat2, lon2, pos) {
    document.getElementById('demo').textContent = "Distance: " + getDistance(lat1, lon1, lat2, lon2, success);
  }
  final(getDistance);
</script>
blex
  • 24,941
  • 5
  • 39
  • 72
  • 2
    You're only calling `final(getDistance);` with a single parameters, so all the rest is undefined (`success`, `lat1`, `lat2`, ...). And your `success` function does nothing at all. It declares variables that cannot be accessible from outside, and does nothing with them, does not return anything – blex Jan 14 '21 at 20:43
  • If I put other parameters there, the error occurs: Uncaught ReferenceError: lat1 is not defined – aciddioxide Jan 14 '21 at 20:49
  • 1
    Because it is undefined as well. You never declare a `lat1` variable that is accessible outside of the `success` function. Also note that [`getCurrentPosition` is asynchronous](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API#getting_the_current_position). So your `final` function is called before the `success` function had a chance to be executed – blex Jan 14 '21 at 20:51
  • 1
    I think you should read this before anything else...: https://developer.mozilla.org/en-US/docs/Glossary/Scope – nanquim Jan 14 '21 at 20:54

1 Answers1

0

There are multiple issues:

  • getCurrentPosition is asynchronous. By the time you call final, success has not yet been executed.
  • Your success function declares local variables. They cannot be used outside of it
  • You call final with a single parameter, not providing it lat1, lat2...

Here is a CodePen demo (StackSnippets don't allow using the location).

And a fixed version of the code:

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};
navigator.geolocation.getCurrentPosition(success, error, options);

function success(pos) {
  var lat1 = pos.coords.latitude;
  var lon1 = pos.coords.longitude;
  var lat2 = 50; //Sample target latitude
  var lon2 = 20; //Sample target longitude

  final(getDistance, lat1, lon1, lat2, lon2); // <-- call it from here
}

function error(err) {
  document.getElementById("demo").textContent = "Error.";
}

//haversine formula

function getDistance(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);
}

function final(getDistance, lat1, lon1, lat2, lon2) {
  document.getElementById("demo").textContent = "Distance: " + getDistance(lat1, lon1, lat2, lon2);
}
blex
  • 24,941
  • 5
  • 39
  • 72