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
Due to rounding of float number, 1-a might be a negative value.
Please replace line:
to: