Using the Haversine Formula in Javascript

javascript haversine formula
formula to calculate distance between two latitude and longitude
haversine formula calculator
haversine formula matlab
haversine formula derivation
haversine formula java
javascript calculate distance between two addresses
haversine formula python

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!

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

Calculate distance and bearing between two Latitude/Longitude , This uses the 'haversine' formula to calculate the great-circle distance between In fact, JavaScript (and most modern computers & languages) use 'IEEE 754'  The Haversine formula is useful for basic proximity, but is insufficient for many use cases, especially within cities. For a more accurate travel distance, we’ll need to use another feature of the Maps JavaScript API. Get Directions with the Maps JavaScript API

Here's a refactored function based on 3 of the other answers!

Please note that the coords arguments are [longitude, latitude].

function haversineDistance(coords1, coords2, isMiles) {
  function toRad(x) {
    return x * Math.PI / 180;
  }

  var lon1 = coords1[0];
  var lat1 = coords1[1];

  var lon2 = coords2[0];
  var lat2 = coords2[1];

  var R = 6371; // km

  var x1 = lat2 - lat1;
  var dLat = toRad(x1);
  var x2 = lon2 - lon1;
  var dLon = toRad(x2)
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(toRad(lat1)) * Math.cos(toRad(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;

  if(isMiles) d /= 1.60934;

  return d;
}

Calculate the Distance between Two Points in your Web Apps, The JavaScript version of the Haversine formula as implemented by the GeoDataSource.com site is Using the JavaScript distance() Function. JavaScript Calculate Distance Between Latitude Longitude Points : Distance between two lat lon points can be calculated using the Haversine formula. Here in this tutorial we are going to explain how you can create a function to get the distance between two lat lon points. We are going explain this with example & online demo.

Why not try the straight forward solution? Instead of extending Number prototype, just define toRad as a regular function:

function toRad(x) {
   return x * Math.PI / 180;
}

and then call toRad everywhere:

var dLat = toRad(lat2-lat1); 

Extending the Number prototype does not always work as expected. For example calling 123.toRad() does not work. I think that if you do var x1 = lat2 - lat1; x1.toRad(); works better than doing (lat2-lat1).toRad()

Haversine formula, JavaScript and Python functions to calculate the distance between two latitude/​longitude locations using the Haversine Formula. MIT-released. haversine Small Java class for calculating the distance between two points using the Haversine formula. public static double distance( double startLat, double startLong, double endLat, double endLong)

ES6 JavaScript/NodeJS refactored version:

   /**
     * Calculates the haversine distance between point A, and B.
     * @param {number[]} latlngA [lat, lng] point A
     * @param {number[]} latlngB [lat, lng] point B
     * @param {boolean} isMiles If we are using miles, else km.
     */
    const haversineDistance = ([lat1, lon1], [lat2, lon2], isMiles = false) => {
      const toRadian = angle => (Math.PI / 180) * angle;
      const distance = (a, b) => (Math.PI / 180) * (a - b);
      const RADIUS_OF_EARTH_IN_KM = 6371;

      const dLat = distance(lat2, lat1);
      const dLon = distance(lon2, lon1);

      lat1 = toRadian(lat1);
      lat2 = toRadian(lat2);

      // Haversine Formula
      const a =
        Math.pow(Math.sin(dLat / 2), 2) +
        Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);
      const c = 2 * Math.asin(Math.sqrt(a));

      let finalDistance = RADIUS_OF_EARTH_IN_KM * c;

      if (isMiles) {
        finalDistance /= 1.60934;
      }

      return finalDistance;
    };

See codepen for tests against accepted answer: https://codepen.io/harrymt/pen/dyYvLpJ?editors=1011

Lat/Lng Distance Functions in JavaScript/Python, Using the JavaScript equivalent of the Haversine formula, we can determine the length of the Polyline, the straight distance between our two  The GeoDataSource.com site has implementations of the Haversine formula for a variety of languages, including Java, JavaScript, PHP, Perl, SQL, and others. I included the JavaScript and Java versions here because those are the two primary mobile app development languages.

when I put this below the function

You only need to put it above the point where you call test(). Where the test function itself is declared does not matter.

Calculating distance with the Maps Javascript API, A simple haversine formula module for Node.js - http://www.npmjs.org/haversine · haversine haversine-formula javascript nodejs. Star 224. Watch  It is important for use in navigation. The haversine can be expressed in trignometric function as: The haversine of the central angle (which is d/r) is calculated by the following formula: where r is the radius of earth (6371 km), d is the distance between two points, is latitude of the two points and is longitude of the two points respectively. Solving d by applying the inverse haversine or by using the inverse sine function, we get:

njj/haversine: A simple haversine formula module for Node.js, JS: Haversine Formula Distance Between Lat,Lng Points in Km. function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {. var R = 6371; // Radius of the earth  The haversine function hav(θ) for some angle θ is a shorthand for sin 2 (θ/2). Given two points on a sphere and θ being the flat angle between radii connecting those points with the center of the sphere, the haversine formula expresses the haversine function with the lattitude (φ) and longitude (λ) values of those points.

JS: Haversine Formula Distance Between Lat,Lng Points in Km , Given two points on the surface of a sphere the Haversine Formula can be used to find the shortest distance between the points. Well what do  Distance. This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is, the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points (ignoring any hills they fly over, of course!).

Client Side (JavaScript) Implementation of the Haversine Formula , Haversine formula in Javascript. In meters. Nothing more. - dcousens/haversine-distance

Comments
  • The accepted answer to this question seems to answer this well, with reference to the same link given by the OP: stackoverflow.com/questions/365826/…
  • I encountered the same problem. I defined a toRadians() as a utility function and computed dLat and dLon like this: toRadians(lat1 - lat2) ... This gave me the wrong answer vs explicitly computing the difference first up and storing it in a variable. Why is that?
  • I don't know why that happens either @Parijat Kalia, I had the same problem.
  • one thing that tripped me up with your function, you are expecting: haversineDistance([lng, lat], [lng, lat], isMiles);
  • Again, not sure if I've implemented something wrong but this answer gives an inaccurate result whereas the currently accepted answer, without refactoring, gives the same result as Google Maps. See my comment on @Harry Mumford-Turner's answer for more detail.
  • You're accessing the 1st element of the latlngA and latlngB parameters to calculate the delta of the latitude, but the docblock for the function states that the 1st element is the longitude.
  • I got an inaccurate result using this solution when testing against Google Maps for the following coords: const latlngA = [52.375603, 4.903206]; const latlngB = [52.366059, 4.926692]; This solution returns 2.8km whereas the currently accepted answer correctly returns 1.92km (which closely matches the 1.91km given by Google Maps).
  • @bigsee thank you, I have fixed the formula to be more accurate and understandable
  • this is the most accurate I have seen on stack and matches up with googlemaps perfectly, well done
  • That is some nice clean code right there. I look forward to testing it when I get home
  • No, it does not need to be put before the function definition.
  • @bergi - sorry you are right - it needs to be defined before the function is called - will edit my answer.
  • Is this still in km? It should be commented as such, as well as the change required to make it return miles.