Reputation: 70
I have a function to calculate the distance between two sets of latitude and longitude coordinates I get from the Google Maps API
Here is the calculate distance function:
function getDistance(lat1, lon1, lat2, lon2) {
var lat1p = parseFloat(lat1);
var lon1p = parseFloat(lon1);
var lat2p = parseFloat(lat2);
var lon2p = parseFloat(lon2);
var R = 6371; // km (change this constant to get miles)
var dLat = (lat2p-lat1p) * Math.PI / 180;
var dLon = (lon2p-lon1p) * Math.PI / 180;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * 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;
if (d>1) return Math.round(d)+"km";
else if (d<=1) return Math.round(d*1000)+"m";
return d;
}
I believe all the coordinates are considered Float types I'm not 100% sure but when I have it print or alert what the distance is it returns NaN.... Is there a way to do this. I'm trying to stray away from the Google Maps API to calculate distance because that would make everything harder because I would essentially have to start over.
Upvotes: 0
Views: 851
Reputation: 70
I'm sorry I fixed it I was double declaring variables as well as I had a . instead of a , when I called the distance function. Thank you guys for your suggestions they led me to figure it out.
Upvotes: 1