0

So I have the following piece of javascript, and I have no idea why I keep getting Nan whenever I try to console log stuff inside the distance function. Even if I just log lat1, I'm getting NaN. But this only happens inside the getDistance function, anywhere else all is working fine. Obviously the rest of the function isn't working as well since everything returns NaN.

(function(){

    var lat = 52.387388 ; //example lat 
    var lon = 4.646219 ;  //example lon

    function initCoords() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(createLatLong);
        } else {
        showError("Your browser does not support Geolocation!");
        }
    }

    function createLatLong(position) {
        var lat2 = position.coords.latitude;
        var long2 = position.coords.longitude;
        console.log(lat + "createLatLong");
        getDistance();
    }

    function getDistance(lat, lon, lat2, long2) {
        var R = 6371;
        var dLat = (lat2-lat) * Math.PI / 180;
        var dLon = (long2-lon) * Math.PI / 180;
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(lat * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
            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; }     

    window.onload = initCoords; 

})();

Here's a fiddle

Pointy
  • 405,095
  • 59
  • 585
  • 614
Bart S.
  • 129
  • 2
  • 9

2 Answers2

2

You're declaring the "getDistance()" function with parameters that hide the variables declared outside the function. Either pass the parameters in when you call it:

 getDistance(lat, lon, lat2, long2);

or else get rid of the formal parameters in the function declaration.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

Due to rounding of float number, 1-a might be a negative value.

Please replace line:

var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

to:

var tan2 = 1-a;
if (tan2 < 0) {
    tan2 = 0;
}
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(tan2));
Michael C.
  • 1,410
  • 1
  • 9
  • 20