Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  188] [ 5]  / answers: 1 / hits: 53711  / 12 Years ago, mon, january 28, 2013, 12:00:00

I'm trying to use the Haversine Distance Formula (as found here: http://www.movable-type.co.uk/scripts/latlong.html) but I can't get it to work, please see the following code



    function test() { 
var lat2 = 42.741;
var lon2 = -71.3161;
var lat1 = 42.806911;
var lon1 = -71.290611;

var R = 6371; // km
//has a problem with the .toRad() method below.
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;

alert(d);
}


And the error is:



Uncaught TypeError: Object -0.06591099999999983 has no method 'toRad' 


Which I understand to be because it needs to do the following:



Number.prototype.toRad = function() {
return this * Math.PI / 180;
}


But when I put this below the function, it still comes back with the same error message. How do I make it use the helper method? Or is there an alternative way to code this to get it to work? Thanks!


More From » haversine

 Answers
8

This code is working:



Number.prototype.toRad = function() {
return this * Math.PI / 180;
}

var lat2 = 42.741;
var lon2 = -71.3161;
var lat1 = 42.806911;
var lon1 = -71.290611;

var R = 6371; // km
//has a problem with the .toRad() method below.
var x1 = lat2-lat1;
var dLat = x1.toRad();
var x2 = lon2-lon1;
var dLon = x2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;

alert(d);


Notice how I defined x1 and x2.
Play with it at: https://tinker.io/3f794


[#80579] Saturday, January 26, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jenamackennac

Total Points: 304
Total Questions: 110
Total Answers: 107

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
jenamackennac questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Wed, Apr 21, 21, 00:00, 3 Years ago
Thu, Apr 1, 21, 00:00, 3 Years ago
Tue, Feb 2, 21, 00:00, 3 Years ago
;