<p>How do I calculate the distance between two points specified by latitude and longitude?</p>

<p>For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to understand the relative accuracies of the approaches available.</p>

[{'answer_id': 27943, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 11, 'selected': True, 'text': '<p>This <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="noreferrer">link</a> might be helpful to you, as it details the use of the <a href="http://en.wikipedia.org/wiki/Haversine_formula" rel="noreferrer">Haversine formula</a> to calculate the distance.</p>\n\n<p>Excerpt:</p>\n\n\n\n<blockquote>\n  <p>This script [in Javascript] calculates great-circle distances between the two points –\n  that is, the shortest distance over the earth’s surface – using the\n  ‘Haversine’ formula.</p>\n</blockquote>\n\n<pre class="lang-js prettyprint-override"><code>function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {\n  var R = 6371; // Radius of the earth in km\n  var dLat = deg2rad(lat2-lat1);  // deg2rad below\n  var dLon = deg2rad(lon2-lon1); \n  var a = \n    Math.sin(dLat/2) * Math.sin(dLat/2) +\n    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * \n    Math.sin(dLon/2) * Math.sin(dLon/2)\n    ; \n  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n  var d = R * c; // Distance in km\n  return d;\n}\n\nfunction deg2rad(deg) {\n  return deg * (Math.PI/180)\n}\n</code></pre>\n'}, {'answer_id': 215848, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>To calculate the distance between two points on a sphere you need to do the <a href="http://en.wikipedia.org/wiki/Great-circle_distance" rel="nofollow noreferrer">Great Circle calculation</a>. </p>\n\n<p>There are a number of C/C++ libraries to help with map projection at <a href="http://www.maptools.org/" rel="nofollow noreferrer">MapTools</a> if you need to reproject your distances to a flat surface.  To do this you will need the projection string of the various coordinate systems.</p>\n\n<p>You may also find <a href="http://www.mapwindow.org/" rel="nofollow noreferrer">MapWindow</a> a useful tool to visualise the points.  Also as its open source its a useful guide to how to use the proj.dll library, which appears to be the core open source projection library.</p>\n'}, {'answer_id': 215849, 'author': 'jaircazarin-old-account', 'author_id': 20915, 'author_profile': 'https://Stackoverflow.com/users/20915', 'pm_score': 6, 'selected': False, 'text': '<p>Here is a C# Implementation:</p>\n\n<pre class="lang-cs prettyprint-override"><code>static class DistanceAlgorithm\n{\n    const double PIx = 3.141592653589793;\n    const double RADIUS = 6378.16;\n\n    /// &lt;summary&gt;\n    /// Convert degrees to Radians\n    /// &lt;/summary&gt;\n    /// &lt;param name="x"&gt;Degrees&lt;/param&gt;\n    /// &lt;returns&gt;The equivalent in radians&lt;/returns&gt;\n    public static double Radians(double x)\n    {\n        return x * PIx / 180;\n    }\n\n    /// &lt;summary&gt;\n    /// Calculate the distance between two places.\n    /// &lt;/summary&gt;\n    /// &lt;param name="lon1"&gt;&lt;/param&gt;\n    /// &lt;param name="lat1"&gt;&lt;/param&gt;\n    /// &lt;param name="lon2"&gt;&lt;/param&gt;\n    /// &lt;param name="lat2"&gt;&lt;/param&gt;\n    /// &lt;returns&gt;&lt;/returns&gt;\n    public static double DistanceBetweenPlaces(\n        double lon1,\n        double lat1,\n        double lon2,\n        double lat2)\n    {\n        double dlon = Radians(lon2 - lon1);\n        double dlat = Radians(lat2 - lat1);\n\n        double a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos(Radians(lat1)) * Math.Cos(Radians(lat2)) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));\n        double angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));\n        return angle * RADIUS;\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 4377364, 'author': 'Stephen Watson', 'author_id': 485514, 'author_profile': 'https://Stackoverflow.com/users/485514', 'pm_score': 5, 'selected': False, 'text': '<p>Thanks very much for all this. I used the following code in my Objective-C iPhone app:</p>\n\n\n\n<pre class="lang-c prettyprint-override"><code>const double PIx = 3.141592653589793;\nconst double RADIO = 6371; // Mean radius of Earth in Km\n\ndouble convertToRadians(double val) {\n\n   return val * PIx / 180;\n}\n\n-(double)kilometresBetweenPlace1:(CLLocationCoordinate2D) place1 andPlace2:(CLLocationCoordinate2D) place2 {\n\n        double dlon = convertToRadians(place2.longitude - place1.longitude);\n        double dlat = convertToRadians(place2.latitude - place1.latitude);\n\n        double a = ( pow(sin(dlat / 2), 2) + cos(convertToRadians(place1.latitude))) * cos(convertToRadians(place2.latitude)) * pow(sin(dlon / 2), 2);\n        double angle = 2 * asin(sqrt(a));\n\n        return angle * RADIO;\n}\n</code></pre>\n\n<p>Latitude and Longitude are in decimal. I didn\'t use min() for the asin() call as the distances that I\'m using are so small that they don\'t require it.</p>\n\n<p>It gave incorrect answers until I passed in the values in Radians - now it\'s pretty much the same as the values obtained from Apple\'s Map app :-)</p>\n\n<p>Extra update:</p>\n\n<p>If you are using iOS4 or later then Apple provide some methods to do this so the same functionality would be achieved with:</p>\n\n<pre class="lang-c prettyprint-override"><code>-(double)kilometresBetweenPlace1:(CLLocationCoordinate2D) place1 andPlace2:(CLLocationCoordinate2D) place2 {\n\n    MKMapPoint  start, finish;\n\n\n    start = MKMapPointForCoordinate(place1);\n    finish = MKMapPointForCoordinate(place2);\n\n    return MKMetersBetweenMapPoints(start, finish) / 1000;\n}\n</code></pre>\n'}, {'answer_id': 9676337, 'author': 'conualfy', 'author_id': 703474, 'author_profile': 'https://Stackoverflow.com/users/703474', 'pm_score': 5, 'selected': False, 'text': '<p>I post here my working example.</p>\n\n<p>List all points in table having distance between a designated point (we use a random point - lat:45.20327, long:23.7806) less than 50 KM, with latitude &amp; longitude, in MySQL (the table fields are coord_lat and coord_long):</p>\n\n<p><strong>List all having DISTANCE&lt;50, in Kilometres (considered Earth radius 6371 KM):</strong></p>\n\n<pre class="lang-sql prettyprint-override"><code>SELECT denumire, (6371 * acos( cos( radians(45.20327) ) * cos( radians( coord_lat ) ) * cos( radians( 23.7806 ) - radians(coord_long) ) + sin( radians(45.20327) ) * sin( radians(coord_lat) ) )) AS distanta \nFROM obiective \nWHERE coord_lat&lt;&gt;\'\' \n    AND coord_long&lt;&gt;\'\' \nHAVING distanta&lt;50 \nORDER BY distanta desc\n</code></pre>\n\n<p>The above example was tested in MySQL 5.0.95 and 5.5.16 (Linux). </p>\n'}, {'answer_id': 11178145, 'author': 'tony gil', 'author_id': 1166727, 'author_profile': 'https://Stackoverflow.com/users/1166727', 'pm_score': 5, 'selected': False, 'text': '<p>This is a simple PHP function that will give a very reasonable approximation (under +/-1% error margin).  </p>\n\n<pre class="lang-php prettyprint-override"><code>&lt;?php\nfunction distance($lat1, $lon1, $lat2, $lon2) {\n\n    $pi80 = M_PI / 180;\n    $lat1 *= $pi80;\n    $lon1 *= $pi80;\n    $lat2 *= $pi80;\n    $lon2 *= $pi80;\n\n    $r = 6372.797; // mean radius of Earth in km\n    $dlat = $lat2 - $lat1;\n    $dlon = $lon2 - $lon1;\n    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);\n    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));\n    $km = $r * $c;\n\n    //echo \'&lt;br/&gt;\'.$km;\n    return $km;\n}\n?&gt;\n</code></pre>\n\n<p>As said before; the earth is NOT a sphere.  It is like an old, old baseball that Mark McGwire decided to practice with - it is full of dents and bumps.  The simpler calculations (like this) treat it like a sphere.</p>\n\n<p>Different methods may be more or less precise according to where you are on this irregular ovoid AND how far apart your points are (the closer they are the smaller the absolute error margin).  The more precise your expectation, the more complex the math.</p>\n\n<p>For more info: <a href="http://en.wikipedia.org/wiki/Geographical_distance" rel="noreferrer">wikipedia geographic distance</a></p>\n'}, {'answer_id': 12600225, 'author': 'whostolebenfrog', 'author_id': 599936, 'author_profile': 'https://Stackoverflow.com/users/599936', 'pm_score': 6, 'selected': False, 'text': '<p>Here is a java implementation of the Haversine formula.</p>\n\n<pre class="lang-java prettyprint-override"><code>public final static double AVERAGE_RADIUS_OF_EARTH_KM = 6371;\npublic int calculateDistanceInKilometer(double userLat, double userLng,\n  double venueLat, double venueLng) {\n\n    double latDistance = Math.toRadians(userLat - venueLat);\n    double lngDistance = Math.toRadians(userLng - venueLng);\n\n    double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)\n      + Math.cos(Math.toRadians(userLat)) * Math.cos(Math.toRadians(venueLat))\n      * Math.sin(lngDistance / 2) * Math.sin(lngDistance / 2);\n\n    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n    return (int) (Math.round(AVERAGE_RADIUS_OF_EARTH_KM * c));\n}\n</code></pre>\n\n<p>Note that here we are rounding the answer to the nearest km.</p>\n'}, {'answer_id': 12930877, 'author': 'bherto39', 'author_id': 1531382, 'author_profile': 'https://Stackoverflow.com/users/1531382', 'pm_score': 0, 'selected': False, 'text': '<p>Here\'s a simple javascript function that may be useful from this <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="nofollow">link</a>.. somehow related but we\'re using google earth javascript plugin instead of maps</p>\n\n<pre><code>function getApproximateDistanceUnits(point1, point2) {\n\n    var xs = 0;\n    var ys = 0;\n\n    xs = point2.getX() - point1.getX();\n    xs = xs * xs;\n\n    ys = point2.getY() - point1.getY();\n    ys = ys * ys;\n\n    return Math.sqrt(xs + ys);\n}\n</code></pre>\n\n<p>The units tho are not in distance but in terms of a ratio relative to your coordinates.  There are other computations related you can substitute for the getApproximateDistanceUnits function <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="nofollow">link here</a></p>\n\n<p>Then I use this function  to see if a latitude longitude is within the radius</p>\n\n<pre><code>function isMapPlacemarkInRadius(point1, point2, radi) {\n    if (point1 &amp;&amp; point2) {\n        return getApproximateDistanceUnits(point1, point2) &lt;= radi;\n    } else {\n        return 0;\n    }\n}\n</code></pre>\n\n<p>point may be defined as</p>\n\n<pre><code> $$.getPoint = function(lati, longi) {\n        var location = {\n            x: 0,\n            y: 0,\n            getX: function() { return location.x; },\n            getY: function() { return location.y; }\n        };\n        location.x = lati;\n        location.y = longi;\n\n        return location;\n    };\n</code></pre>\n\n<p>then you can do your thing to see if a point is within a region with a radius say:</p>\n\n<pre><code> //put it on the map if within the range of a specified radi assuming 100,000,000 units\n        var iconpoint = Map.getPoint(pp.latitude, pp.longitude);\n        var centerpoint = Map.getPoint(Settings.CenterLatitude, Settings.CenterLongitude);\n\n        //approx ~200 units to show only half of the globe from the default center radius\n        if (isMapPlacemarkInRadius(centerpoint, iconpoint, 120)) {\n            addPlacemark(pp.latitude, pp.longitude, pp.name);\n        }\n        else {\n            otherSidePlacemarks.push({\n                latitude: pp.latitude,\n                longitude: pp.longitude,\n                name: pp.name\n            });\n\n        }\n</code></pre>\n'}, {'answer_id': 14329945, 'author': 'ayalcinkaya', 'author_id': 1589731, 'author_profile': 'https://Stackoverflow.com/users/1589731', 'pm_score': 2, 'selected': False, 'text': '<p>there is a good example in here to calculate distance with PHP <a href="http://www.geodatasource.com/developers/php" rel="nofollow">http://www.geodatasource.com/developers/php</a> :</p>\n\n<pre><code> function distance($lat1, $lon1, $lat2, $lon2, $unit) {\n\n     $theta = $lon1 - $lon2;\n     $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));\n     $dist = acos($dist);\n     $dist = rad2deg($dist);\n     $miles = $dist * 60 * 1.1515;\n     $unit = strtoupper($unit);\n\n     if ($unit == "K") {\n         return ($miles * 1.609344);\n     } else if ($unit == "N") {\n          return ($miles * 0.8684);\n     } else {\n          return $miles;\n     }\n }\n</code></pre>\n'}, {'answer_id': 15759519, 'author': 'Taiseer Joudeh', 'author_id': 3625265, 'author_profile': 'https://Stackoverflow.com/users/3625265', 'pm_score': 2, 'selected': False, 'text': '<p>Here is the implementation VB.NET, this implementation will give you the result in KM or Miles based on an Enum value you pass.</p>\n\n<pre><code>Public Enum DistanceType\n    Miles\n    KiloMeters\nEnd Enum\n\nPublic Structure Position\n    Public Latitude As Double\n    Public Longitude As Double\nEnd Structure\n\nPublic Class Haversine\n\n    Public Function Distance(Pos1 As Position,\n                             Pos2 As Position,\n                             DistType As DistanceType) As Double\n\n        Dim R As Double = If((DistType = DistanceType.Miles), 3960, 6371)\n\n        Dim dLat As Double = Me.toRadian(Pos2.Latitude - Pos1.Latitude)\n\n        Dim dLon As Double = Me.toRadian(Pos2.Longitude - Pos1.Longitude)\n\n        Dim a As Double = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(Me.toRadian(Pos1.Latitude)) * Math.Cos(Me.toRadian(Pos2.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)\n\n        Dim c As Double = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)))\n\n        Dim result As Double = R * c\n\n        Return result\n\n    End Function\n\n    Private Function toRadian(val As Double) As Double\n\n        Return (Math.PI / 180) * val\n\n    End Function\n\nEnd Class\n</code></pre>\n'}, {'answer_id': 17078193, 'author': 'Kache', 'author_id': 234593, 'author_profile': 'https://Stackoverflow.com/users/234593', 'pm_score': 2, 'selected': False, 'text': '<p>I condensed the computation down by simplifying the formula.</p>\n\n<p>Here it is in Ruby:</p>\n\n<pre><code>include Math\nearth_radius_mi = 3959\nradians = lambda { |deg| deg * PI / 180 }\ncoord_radians = lambda { |c| { :lat =&gt; radians[c[:lat]], :lng =&gt; radians[c[:lng]] } }\n\n# from/to = { :lat =&gt; (latitude_in_degrees), :lng =&gt; (longitude_in_degrees) }\ndef haversine_distance(from, to)\n  from, to = coord_radians[from], coord_radians[to]\n  cosines_product = cos(to[:lat]) * cos(from[:lat]) * cos(from[:lng] - to[:lng])\n  sines_product = sin(to[:lat]) * sin(from[:lat])\n  return earth_radius_mi * acos(cosines_product + sines_product)\nend\n</code></pre>\n'}, {'answer_id': 17315408, 'author': 'Andre Cytryn', 'author_id': 1165337, 'author_profile': 'https://Stackoverflow.com/users/1165337', 'pm_score': 3, 'selected': False, 'text': '<p>You can use the build in CLLocationDistance to calculate this:</p>\n\n<pre><code>CLLocation *location1 = [[CLLocation alloc] initWithLatitude:latitude1 longitude:longitude1];\nCLLocation *location2 = [[CLLocation alloc] initWithLatitude:latitude2 longitude:longitude2];\n[self distanceInMetersFromLocation:location1 toLocation:location2]\n\n- (int)distanceInMetersFromLocation:(CLLocation*)location1 toLocation:(CLLocation*)location2 {\n    CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];\n    return distanceInMeters;\n}\n</code></pre>\n\n<p>In your case if you want kilometers just divide by 1000.</p>\n'}, {'answer_id': 19772119, 'author': 'Arturo Hernandez', 'author_id': 937703, 'author_profile': 'https://Stackoverflow.com/users/937703', 'pm_score': 4, 'selected': False, 'text': '<p>The haversine is definitely a good formula for probably most cases, other answers already include it so I am not going to take the space. But it is important to note that no matter what formula is used (yes not just one). Because of the huge range of accuracy possible as well as the computation time required. The choice of formula requires a bit more thought than a simple no brainer answer. </p>\n\n<p>This posting from a person at nasa, is the best one I found at discussing the options</p>\n\n<p><a href="http://www.cs.nyu.edu/visual/home/proj/tiger/gisfaq.html" rel="noreferrer">http://www.cs.nyu.edu/visual/home/proj/tiger/gisfaq.html</a></p>\n\n<p>For example, if you are just sorting rows by distance in a 100 miles radius. The flat earth formula will be much faster than the haversine.</p>\n\n<pre><code>HalfPi = 1.5707963;\nR = 3956; /* the radius gives you the measurement unit*/\n\na = HalfPi - latoriginrad;\nb = HalfPi - latdestrad;\nu = a * a + b * b;\nv = - 2 * a * b * cos(longdestrad - longoriginrad);\nc = sqrt(abs(u + v));\nreturn R * c;\n</code></pre>\n\n<p>Notice there is just one cosine and one square root. Vs 9 of them on the Haversine formula.</p>\n'}, {'answer_id': 19852967, 'author': 'MPaulo', 'author_id': 1105558, 'author_profile': 'https://Stackoverflow.com/users/1105558', 'pm_score': 2, 'selected': False, 'text': "<pre><code>function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2,units) {\n  var R = 6371; // Radius of the earth in km\n  var dLat = deg2rad(lat2-lat1);  // deg2rad below\n  var dLon = deg2rad(lon2-lon1); \n  var a = \n    Math.sin(dLat/2) * Math.sin(dLat/2) +\n    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * \n    Math.sin(dLon/2) * Math.sin(dLon/2)\n    ; \n  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n  var d = R * c; \n  var miles = d / 1.609344; \n\nif ( units == 'km' ) {  \nreturn d; \n } else {\nreturn miles;\n}}\n</code></pre>\n\n<p>Chuck's solution, valid for miles also.</p>\n"}, {'answer_id': 21623206, 'author': 'Salvador Dali', 'author_id': 1090562, 'author_profile': 'https://Stackoverflow.com/users/1090562', 'pm_score': 9, 'selected': False, 'text': '<p>I needed to calculate a lot of distances between the points for my project, so I went ahead and tried to optimize the code, I have found here. On average in different browsers my new implementation <strong>runs 2 times faster</strong> than the most upvoted answer.</p>\n<pre class="lang-js prettyprint-override"><code>function distance(lat1, lon1, lat2, lon2) {\n  var p = 0.017453292519943295;    // Math.PI / 180\n  var c = Math.cos;\n  var a = 0.5 - c((lat2 - lat1) * p)/2 + \n          c(lat1 * p) * c(lat2 * p) * \n          (1 - c((lon2 - lon1) * p))/2;\n\n  return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km\n}\n</code></pre>\n<p>You can play with my jsPerf and see the <a href="http://jsperf.com/haversine-salvador/8" rel="noreferrer">results here</a>.</p>\n<p>Recently I needed to do the same in python, so here is a <strong>python implementation</strong>:</p>\n<pre class="lang-python prettyprint-override"><code>from math import cos, asin, sqrt, pi\n\ndef distance(lat1, lon1, lat2, lon2):\n    p = pi/180\n    a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2\n    return 12742 * asin(sqrt(a)) #2*R*asin...\n</code></pre>\n<p>And for the sake of completeness: <a href="https://en.wikipedia.org/wiki/Haversine_formula" rel="noreferrer">Haversine</a> on Wikipedia.</p>\n'}, {'answer_id': 21739328, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Here is my java implementation for calculation distance via decimal degrees after some search. I used mean radius of world (from wikipedia) in km. İf you want result miles then use world radius in miles.</p>\n\n<pre><code>public static double distanceLatLong2(double lat1, double lng1, double lat2, double lng2) \n{\n  double earthRadius = 6371.0d; // KM: use mile here if you want mile result\n\n  double dLat = toRadian(lat2 - lat1);\n  double dLng = toRadian(lng2 - lng1);\n\n  double a = Math.pow(Math.sin(dLat/2), 2)  + \n          Math.cos(toRadian(lat1)) * Math.cos(toRadian(lat2)) * \n          Math.pow(Math.sin(dLng/2), 2);\n\n  double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n\n  return earthRadius * c; // returns result kilometers\n}\n\npublic static double toRadian(double degrees) \n{\n  return (degrees * Math.PI) / 180.0d;\n}\n</code></pre>\n'}, {'answer_id': 23095329, 'author': 'Jaap', 'author_id': 2204410, 'author_profile': 'https://Stackoverflow.com/users/2204410', 'pm_score': 5, 'selected': False, 'text': '<p>In the other answers an implementation in <a href="/questions/tagged/r" class="post-tag" title="show questions tagged &#39;r&#39;" rel="tag">r</a> is missing.</p>\n\n<p>Calculating the distance between two point is quite straightforward with the <code>distm</code> function from the <code>geosphere</code> package:</p>\n\n<pre><code>distm(p1, p2, fun = distHaversine)\n</code></pre>\n\n<p>where:</p>\n\n<pre><code>p1 = longitude/latitude for point(s)\np2 = longitude/latitude for point(s)\n# type of distance calculation\nfun = distCosine / distHaversine / distVincentySphere / distVincentyEllipsoid \n</code></pre>\n\n<p>As the earth is not perfectly spherical, the <a href="http://en.wikipedia.org/wiki/Vincenty%27s_formulae" rel="noreferrer">Vincenty formula for ellipsoids</a> is probably the best way to calculate distances. Thus in the <code>geosphere</code> package you use then:</p>\n\n<pre><code>distm(p1, p2, fun = distVincentyEllipsoid)\n</code></pre>\n\n<hr>\n\n<p>Off course you don\'t necessarily have to use <code>geosphere</code> package, you can also calculate the distance in base <code>R</code> with a function:</p>\n\n<pre><code>hav.dist &lt;- function(long1, lat1, long2, lat2) {\n  R &lt;- 6371\n  diff.long &lt;- (long2 - long1)\n  diff.lat &lt;- (lat2 - lat1)\n  a &lt;- sin(diff.lat/2)^2 + cos(lat1) * cos(lat2) * sin(diff.long/2)^2\n  b &lt;- 2 * asin(pmin(1, sqrt(a))) \n  d = R * b\n  return(d)\n}\n</code></pre>\n'}, {'answer_id': 23907104, 'author': 'shanavascet', 'author_id': 2286174, 'author_profile': 'https://Stackoverflow.com/users/2286174', 'pm_score': 2, 'selected': False, 'text': '<p>In Mysql use the following function pass the parameters as using  <code>POINT(LONG,LAT)</code></p>\n\n<pre><code>CREATE FUNCTION `distance`(a POINT, b POINT)\n RETURNS double\n    DETERMINISTIC\nBEGIN\n\nRETURN\n\nGLength( LineString(( PointFromWKB(a)), (PointFromWKB(b)))) * 100000; -- To Make the distance in meters\n\nEND;\n</code></pre>\n'}, {'answer_id': 24058134, 'author': 'borchvm', 'author_id': 3115822, 'author_profile': 'https://Stackoverflow.com/users/3115822', 'pm_score': 0, 'selected': False, 'text': '<pre><code>//JAVA\n    public Double getDistanceBetweenTwoPoints(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {\n    final int RADIUS_EARTH = 6371;\n\n    double dLat = getRad(latitude2 - latitude1);\n    double dLong = getRad(longitude2 - longitude1);\n\n    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getRad(latitude1)) * Math.cos(getRad(latitude2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);\n    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n    return (RADIUS_EARTH * c) * 1000;\n    }\n\n    private Double getRad(Double x) {\n    return x * Math.PI / 180;\n    }\n</code></pre>\n'}, {'answer_id': 24846150, 'author': 'Steven Christenson', 'author_id': 2723552, 'author_profile': 'https://Stackoverflow.com/users/2723552', 'pm_score': 3, 'selected': False, 'text': '<p>I don\'t like adding yet another answer, but the Google maps API v.3 has spherical geometry (and more). After converting your WGS84 to decimal degrees you can do this:</p>\n\n<pre><code>&lt;script src="http://maps.google.com/maps/api/js?sensor=false&amp;libraries=geometry" type="text/javascript"&gt;&lt;/script&gt;  \n\ndistance = google.maps.geometry.spherical.computeDistanceBetween(\n    new google.maps.LatLng(fromLat, fromLng), \n    new google.maps.LatLng(toLat, toLng));\n</code></pre>\n\n<p>No word about how accurate Google\'s calculations are or even what model is used (though it does say "spherical" rather than "geoid".  By the way, the "straight line" distance will obviously be different from the distance if one travels on the surface of the earth which is what everyone seems to be presuming.</p>\n'}, {'answer_id': 25266454, 'author': 'Jorik', 'author_id': 1346170, 'author_profile': 'https://Stackoverflow.com/users/1346170', 'pm_score': 0, 'selected': False, 'text': '<p>I\'ve created this small Javascript LatLng object, might be useful for somebody.</p>\n\n<pre><code>var latLng1 = new LatLng(5, 3);\nvar latLng2 = new LatLng(6, 7);\nvar distance = latLng1.distanceTo(latLng2); \n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>/**\n * latLng point\n * @param {Number} lat\n * @param {Number} lng\n * @returns {LatLng}\n * @constructor\n */\nfunction LatLng(lat,lng) {\n    this.lat = parseFloat(lat);\n    this.lng = parseFloat(lng);\n\n    this.__cache = {};\n}\n\nLatLng.prototype = {\n    toString: function() {\n        return [this.lat, this.lng].join(",");\n    },\n\n    /**\n     * calculate distance in km to another latLng, with caching\n     * @param {LatLng} latLng\n     * @returns {Number} distance in km\n     */\n    distanceTo: function(latLng) {\n        var cacheKey = latLng.toString();\n        if(cacheKey in this.__cache) {\n            return this.__cache[cacheKey];\n        }\n\n        // the fastest way to calculate the distance, according to this jsperf test;\n        // http://jsperf.com/haversine-salvador/8\n        // http://stackoverflow.com/questions/27928\n        var deg2rad = 0.017453292519943295; // === Math.PI / 180\n        var lat1 = this.lat * deg2rad;\n        var lng1 = this.lng * deg2rad;\n        var lat2 = latLng.lat * deg2rad;\n        var lng2 = latLng.lng * deg2rad;\n        var a = (\n            (1 - Math.cos(lat2 - lat1)) +\n            (1 - Math.cos(lng2 - lng1)) * Math.cos(lat1) * Math.cos(lat2)\n            ) / 2;\n        var distance = 12742 * Math.asin(Math.sqrt(a)); // Diameter of the earth in km (2 * 6371)\n\n        // cache the distance\n        this.__cache[cacheKey] = distance;\n\n        return distance;\n    }\n};\n</code></pre>\n'}, {'answer_id': 27218153, 'author': 'Eric Walsh', 'author_id': 2577822, 'author_profile': 'https://Stackoverflow.com/users/2577822', 'pm_score': 1, 'selected': False, 'text': "<p>Had an issue with math.deg in LUA...  if anyone knows a fix please clean up this code!  </p>\n\n<p>In the meantime here's an implementation of the Haversine in LUA (use this with Redis!)</p>\n\n<pre><code>function calcDist(lat1, lon1, lat2, lon2)\n    lat1= lat1*0.0174532925\n    lat2= lat2*0.0174532925\n    lon1= lon1*0.0174532925\n    lon2= lon2*0.0174532925\n\n    dlon = lon2-lon1\n    dlat = lat2-lat1\n\n    a = math.pow(math.sin(dlat/2),2) + math.cos(lat1) * math.cos(lat2) * math.pow(math.sin(dlon/2),2)\n    c = 2 * math.asin(math.sqrt(a))\n    dist = 6371 * c      -- multiply by 0.621371 to convert to miles\n    return dist\nend\n</code></pre>\n\n<p>cheers!</p>\n"}, {'answer_id': 29946545, 'author': 'Raphael C', 'author_id': 1872349, 'author_profile': 'https://Stackoverflow.com/users/1872349', 'pm_score': 2, 'selected': False, 'text': '<pre><code>function getDistanceFromLatLonInKm(position1, position2) {\n    &quot;use strict&quot;;\n    var deg2rad = function (deg) { return deg * (Math.PI / 180); },\n        R = 6371,\n        dLat = deg2rad(position2.lat - position1.lat),\n        dLng = deg2rad(position2.lng - position1.lng),\n        a = Math.sin(dLat / 2) * Math.sin(dLat / 2)\n            + Math.cos(deg2rad(position1.lat))\n            * Math.cos(deg2rad(position2.lat))\n            * Math.sin(dLng / 2) * Math.sin(dLng / 2),\n        c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n    return R * c;\n}\n\nconsole.log(getDistanceFromLatLonInKm(\n    {lat: 48.7931459, lng: 1.9483572},\n    {lat: 48.827167, lng: 2.2459745}\n));\n</code></pre>\n'}, {'answer_id': 31398615, 'author': 'invoketheshell', 'author_id': 4930264, 'author_profile': 'https://Stackoverflow.com/users/4930264', 'pm_score': 3, 'selected': False, 'text': "<p><code>pip install haversine</code></p>\n<p>Python implementation</p>\n<p>Origin is the center of the contiguous United States.</p>\n<pre><code>from haversine import haversine, Unit\norigin = (39.50, 98.35)\nparis = (48.8567, 2.3508)\nhaversine(origin, paris, unit=Unit.MILES)\n</code></pre>\n<p>To get the answer in kilometers simply set <code>unit=Unit.KILOMETERS</code> (that's the default).</p>\n"}, {'answer_id': 33090122, 'author': 'Eduardo Naveda', 'author_id': 1472511, 'author_profile': 'https://Stackoverflow.com/users/1472511', 'pm_score': 2, 'selected': False, 'text': "<p>Here's the accepted answer implementation ported to Java in case anyone needs it.</p>\n\n<pre><code>package com.project529.garage.util;\n\n\n/**\n * Mean radius.\n */\nprivate static double EARTH_RADIUS = 6371;\n\n/**\n * Returns the distance between two sets of latitudes and longitudes in meters.\n * &lt;p/&gt;\n * Based from the following JavaScript SO answer:\n * http://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula,\n * which is based on https://en.wikipedia.org/wiki/Haversine_formula (error rate: ~0.55%).\n */\npublic double getDistanceBetween(double lat1, double lon1, double lat2, double lon2) {\n    double dLat = toRadians(lat2 - lat1);\n    double dLon = toRadians(lon2 - lon1);\n\n    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n            Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *\n                    Math.sin(dLon / 2) * Math.sin(dLon / 2);\n    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n    double d = EARTH_RADIUS * c;\n\n    return d;\n}\n\npublic double toRadians(double degrees) {\n    return degrees * (Math.PI / 180);\n}\n</code></pre>\n"}, {'answer_id': 34241873, 'author': 'Sel', 'author_id': 2706338, 'author_profile': 'https://Stackoverflow.com/users/2706338', 'pm_score': 3, 'selected': False, 'text': '<p>Here is a <strong>typescript</strong> implementation of the Haversine formula</p>\n\n<pre><code>static getDistanceFromLatLonInKm(lat1: number, lon1: number, lat2: number, lon2: number): number {\n    var deg2Rad = deg =&gt; {\n        return deg * Math.PI / 180;\n    }\n\n    var r = 6371; // Radius of the earth in km\n    var dLat = deg2Rad(lat2 - lat1);   \n    var dLon = deg2Rad(lon2 - lon1);\n    var a =\n        Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n        Math.cos(deg2Rad(lat1)) * Math.cos(deg2Rad(lat2)) *\n        Math.sin(dLon / 2) * Math.sin(dLon / 2);\n    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n    var d = r * c; // Distance in km\n    return d;\n}\n</code></pre>\n'}, {'answer_id': 35309170, 'author': 'Meymann', 'author_id': 361169, 'author_profile': 'https://Stackoverflow.com/users/361169', 'pm_score': 3, 'selected': False, 'text': "<p>There could be a simpler solution, and more correct: The perimeter of earth is 40,000Km at the equator, about 37,000 on Greenwich (or any longitude) cycle. Thus:</p>\n\n<pre><code>pythagoras = function (lat1, lon1, lat2, lon2) {\n   function sqr(x) {return x * x;}\n   function cosDeg(x) {return Math.cos(x * Math.PI / 180.0);}\n\n   var earthCyclePerimeter = 40000000.0 * cosDeg((lat1 + lat2) / 2.0);\n   var dx = (lon1 - lon2) * earthCyclePerimeter / 360.0;\n   var dy = 37000000.0 * (lat1 - lat2) / 360.0;\n\n   return Math.sqrt(sqr(dx) + sqr(dy));\n};\n</code></pre>\n\n<p>I agree that it should be fine-tuned as, I myself said that it's an ellipsoid, so the radius to be multiplied by the cosine varies. But it's a bit more accurate. Compared with Google Maps and it did reduce the error significantly.</p>\n"}, {'answer_id': 37870363, 'author': 'Keerthana Gopalakrishnan', 'author_id': 4400634, 'author_profile': 'https://Stackoverflow.com/users/4400634', 'pm_score': 3, 'selected': False, 'text': "<p>There is some errors in the code provided, I've fixed it below.</p>\n<p>All the above answers assumes the earth is a sphere. However, a more accurate approximation would be that of an oblate spheroid.</p>\n<pre><code>a= 6378.137#equitorial radius in km\nb= 6356.752#polar radius in km\n\ndef Distance(lat1, lons1, lat2, lons2):\n    lat1=math.radians(lat1)\n    lons1=math.radians(lons1)\n    R1=(((((a**2)*math.cos(lat1))**2)+(((b**2)*math.sin(lat1))**2))/((a*math.cos(lat1))**2+(b*math.sin(lat1))**2))**0.5 #radius of earth at lat1\n    x1=R1*math.cos(lat1)*math.cos(lons1)\n    y1=R1*math.cos(lat1)*math.sin(lons1)\n    z1=R1*math.sin(lat1)\n\n    lat2=math.radians(lat2)\n    lons2=math.radians(lons2)\n    R2=(((((a**2)*math.cos(lat2))**2)+(((b**2)*math.sin(lat2))**2))/((a*math.cos(lat2))**2+(b*math.sin(lat2))**2))**0.5 #radius of earth at lat2\n    x2=R2*math.cos(lat2)*math.cos(lons2)\n    y2=R2*math.cos(lat2)*math.sin(lons2)\n    z2=R2*math.sin(lat2)\n    \n    return ((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)**0.5\n</code></pre>\n"}, {'answer_id': 41257416, 'author': 'fla', 'author_id': 2598693, 'author_profile': 'https://Stackoverflow.com/users/2598693', 'pm_score': 2, 'selected': False, 'text': "<p>here is an example in <strong>postgres</strong> sql (in km, for miles version, replace 1.609344 by 0.8684 version)</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION public.geodistance(alat float, alng float, blat  \n\nfloat, blng  float)\n  RETURNS float AS\n$BODY$\nDECLARE\n    v_distance float;\nBEGIN\n\n    v_distance = asin( sqrt(\n            sin(radians(blat-alat)/2)^2 \n                + (\n                    (sin(radians(blng-alng)/2)^2) *\n                    cos(radians(alat)) *\n                    cos(radians(blat))\n                )\n          )\n        ) * cast('7926.3352' as float) * cast('1.609344' as float) ;\n\n\n    RETURN v_distance;\nEND \n$BODY$\nlanguage plpgsql VOLATILE SECURITY DEFINER;\nalter function geodistance(alat float, alng float, blat float, blng float)\nowner to postgres;\n</code></pre>\n"}, {'answer_id': 42360739, 'author': 'Er.Subhendu Kumar Pati', 'author_id': 7596912, 'author_profile': 'https://Stackoverflow.com/users/7596912', 'pm_score': 3, 'selected': False, 'text': '<p>This script [in PHP] calculates distances between the two points.</p>\n\n<pre><code>public static function getDistanceOfTwoPoints($source, $dest, $unit=\'K\') {\n        $lat1 = $source[0];\n        $lon1 = $source[1];\n        $lat2 = $dest[0];\n        $lon2 = $dest[1];\n\n        $theta = $lon1 - $lon2;\n        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));\n        $dist = acos($dist);\n        $dist = rad2deg($dist);\n        $miles = $dist * 60 * 1.1515;\n        $unit = strtoupper($unit);\n\n        if ($unit == "K") {\n            return ($miles * 1.609344);\n        }\n        else if ($unit == "M")\n        {\n            return ($miles * 1.609344 * 1000);\n        }\n        else if ($unit == "N") {\n            return ($miles * 0.8684);\n        } \n        else {\n            return $miles;\n        }\n    }\n</code></pre>\n'}, {'answer_id': 46771383, 'author': 'aldrien.h', 'author_id': 2534479, 'author_profile': 'https://Stackoverflow.com/users/2534479', 'pm_score': 2, 'selected': False, 'text': "<p>Here's another converted to <strong>Ruby</strong> code:</p>\n\n<pre><code>include Math\n#Note: from/to = [lat, long]\n\ndef get_distance_in_km(from, to)\n  radians = lambda { |deg| deg * Math.PI / 180 }\n  radius = 6371 # Radius of the earth in kilometer\n  dLat = radians[to[0]-from[0]]\n  dLon = radians[to[1]-from[1]]\n\n  cosines_product = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(radians[from[0]]) * Math.cos(radians[to[1]]) * Math.sin(dLon/2) * Math.sin(dLon/2)\n\n  c = 2 * Math.atan2(Math.sqrt(cosines_product), Math.sqrt(1-cosines_product)) \n  return radius * c # Distance in kilometer\nend\n</code></pre>\n"}, {'answer_id': 49916544, 'author': 'Chong Lip Phang', 'author_id': 2435020, 'author_profile': 'https://Stackoverflow.com/users/2435020', 'pm_score': 3, 'selected': False, 'text': "<p>As pointed out, an accurate calculation should take into account that the earth is not a perfect sphere. Here are some comparisons of the various algorithms offered here:</p>\n\n<pre><code>geoDistance(50,5,58,3)\nHaversine: 899 km\nMaymenn: 833 km\nKeerthana: 897 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 900 km\n\ngeoDistance(50,5,-58,-3)\nHaversine: 12030 km\nMaymenn: 11135 km\nKeerthana: 10310 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 12044 km\n\ngeoDistance(.05,.005,.058,.003)\nHaversine: 0.9169 km\nMaymenn: 0.851723 km\nKeerthana: 0.917964 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 0.917964 km\n\ngeoDistance(.05,80,.058,80.3)\nHaversine: 33.37 km\nMaymenn: 33.34 km\nKeerthana: 33.40767 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 33.40770 km\n</code></pre>\n\n<p>Over small distances, Keerthana's algorithm does seem to coincide with that of Google Maps. Google Maps does not seem to follow any simple algorithm, suggesting that it may be the most accurate method here.</p>\n\n<p>Anyway, here is a Javascript implementation of Keerthana's algorithm:</p>\n\n<pre><code>function geoDistance(lat1, lng1, lat2, lng2){\n    const a = 6378.137; // equitorial radius in km\n    const b = 6356.752; // polar radius in km\n\n    var sq = x =&gt; (x*x);\n    var sqr = x =&gt; Math.sqrt(x);\n    var cos = x =&gt; Math.cos(x);\n    var sin = x =&gt; Math.sin(x);\n    var radius = lat =&gt; sqr((sq(a*a*cos(lat))+sq(b*b*sin(lat)))/(sq(a*cos(lat))+sq(b*sin(lat))));\n\n    lat1 = lat1 * Math.PI / 180;\n    lng1 = lng1 * Math.PI / 180;\n    lat2 = lat2 * Math.PI / 180;\n    lng2 = lng2 * Math.PI / 180;\n\n    var R1 = radius(lat1);\n    var x1 = R1*cos(lat1)*cos(lng1);\n    var y1 = R1*cos(lat1)*sin(lng1);\n    var z1 = R1*sin(lat1);\n\n    var R2 = radius(lat2);\n    var x2 = R2*cos(lat2)*cos(lng2);\n    var y2 = R2*cos(lat2)*sin(lng2);\n    var z2 = R2*sin(lat2);\n\n    return sqr(sq(x1-x2)+sq(y1-y2)+sq(z1-z2));\n}\n</code></pre>\n"}, {'answer_id': 50866722, 'author': 'Ryan', 'author_id': 3355222, 'author_profile': 'https://Stackoverflow.com/users/3355222', 'pm_score': 1, 'selected': False, 'text': '<p>FSharp version, using miles: </p>\n\n<pre><code>let radialDistanceHaversine location1 location2 : float = \n                let degreeToRadian degrees = degrees * System.Math.PI / 180.0\n                let earthRadius = 3959.0\n                let deltaLat = location2.Latitude - location1.Latitude |&gt; degreeToRadian\n                let deltaLong = location2.Longitude - location1.Longitude |&gt; degreeToRadian\n                let a =\n                    (deltaLat / 2.0 |&gt; sin) ** 2.0\n                    + (location1.Latitude |&gt; degreeToRadian |&gt; cos)\n                    * (location2.Latitude |&gt; degreeToRadian |&gt; cos)\n                    * (deltaLong / 2.0 |&gt; sin) ** 2.0\n                atan2 (a |&gt; sqrt) (1.0 - a |&gt; sqrt)\n                * 2.0\n                * earthRadius\n</code></pre>\n'}, {'answer_id': 52718561, 'author': 'Kiran Maniya', 'author_id': 8203357, 'author_profile': 'https://Stackoverflow.com/users/8203357', 'pm_score': 3, 'selected': False, 'text': '<p>Here is the SQL Implementation to calculate the distance in km,</p>\n\n<pre><code>SELECT UserId, ( 3959 * acos( cos( radians( your latitude here ) ) * cos( radians(latitude) ) * \ncos( radians(longitude) - radians( your longitude here ) ) + sin( radians( your latitude here ) ) * \nsin( radians(latitude) ) ) ) AS distance FROM user HAVING\ndistance &lt; 5  ORDER BY distance LIMIT 0 , 5;\n</code></pre>\n\n<p>For further details in the implementation by programming langugage, you can just go through the php script given <a href="https://www.geodatasource.com/developers/php" rel="nofollow noreferrer">here</a></p>\n'}, {'answer_id': 54448795, 'author': 'ak-j', 'author_id': 5925898, 'author_profile': 'https://Stackoverflow.com/users/5925898', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>Java implementation in according <a href="https://en.wikipedia.org/wiki/Haversine_formula" rel="nofollow noreferrer">Haversine formula</a></p>\n</blockquote>\n\n<pre class="lang-java prettyprint-override"><code>double calculateDistance(double latPoint1, double lngPoint1, \n                         double latPoint2, double lngPoint2) {\n    if(latPoint1 == latPoint2 &amp;&amp; lngPoint1 == lngPoint2) {\n        return 0d;\n    }\n\n    final double EARTH_RADIUS = 6371.0; //km value;\n\n    //converting to radians\n    latPoint1 = Math.toRadians(latPoint1);\n    lngPoint1 = Math.toRadians(lngPoint1);\n    latPoint2 = Math.toRadians(latPoint2);\n    lngPoint2 = Math.toRadians(lngPoint2);\n\n    double distance = Math.pow(Math.sin((latPoint2 - latPoint1) / 2.0), 2) \n            + Math.cos(latPoint1) * Math.cos(latPoint2)\n            * Math.pow(Math.sin((lngPoint2 - lngPoint1) / 2.0), 2);\n    distance = 2.0 * EARTH_RADIUS * Math.asin(Math.sqrt(distance));\n\n    return distance; //km value\n}\n</code></pre>\n'}, {'answer_id': 55455344, 'author': 'Ramprasath Selvam', 'author_id': 8079610, 'author_profile': 'https://Stackoverflow.com/users/8079610', 'pm_score': 2, 'selected': False, 'text': "<p>One of the main challenges to calculating distances - especially large ones - is accounting for the curvature of the Earth. If only the Earth were flat, calculating the distance between two points would be as simple as for that of a straight line! The Haversine formula includes a constant (it's the R variable below) that represents the radius of the Earth. Depending on whether you are measuring in miles or kilometers, it would equal 3956 mi or 6367 km respectively.<br><br>\nThe basic formula is:<br><br></p>\n<blockquote>\n<pre><code>dlon = lon2 - lon1\ndlat = lat2 - lat1\na = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2\nc = 2 * atan2( sqrt(a), sqrt(1-a) )\ndistance = R * c (where R is the radius of the Earth)\n \nR = 6367 km OR 3956 mi\n</code></pre>\n</blockquote>\n<pre><code>     lat1, lon1: The Latitude and Longitude of point 1 (in decimal degrees)\n     lat2, lon2: The Latitude and Longitude of point 2 (in decimal degrees)\n     unit: The unit of measurement in which to calculate the results where:\n     'M' is statute miles (default)\n     'K' is kilometers\n     'N' is nautical miles\n</code></pre>\n<p>Sample</p>\n<pre><code>function distance(lat1, lon1, lat2, lon2, unit) {\n    try {\n        var radlat1 = Math.PI * lat1 / 180\n        var radlat2 = Math.PI * lat2 / 180\n        var theta = lon1 - lon2\n        var radtheta = Math.PI * theta / 180\n        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);\n        dist = Math.acos(dist)\n        dist = dist * 180 / Math.PI\n        dist = dist * 60 * 1.1515\n        if (unit == &quot;K&quot;) {\n            dist = dist * 1.609344\n        }\n        if (unit == &quot;N&quot;) {\n            dist = dist * 0.8684\n        }\n        return dist\n    } catch (err) {\n        console.log(err);\n    }\n}\n</code></pre>\n"}, {'answer_id': 59646977, 'author': 'Oleg Khalidov', 'author_id': 2450439, 'author_profile': 'https://Stackoverflow.com/users/2450439', 'pm_score': 1, 'selected': False, 'text': '<p>Dart lang:</p>\n\n<pre class="lang-dart prettyprint-override"><code>import \'dart:math\' show cos, sqrt, asin;\n\ndouble calculateDistance(LatLng l1, LatLng l2) {\n  const p = 0.017453292519943295;\n  final a = 0.5 -\n      cos((l2.latitude - l1.latitude) * p) / 2 +\n      cos(l1.latitude * p) *\n          cos(l2.latitude * p) *\n          (1 - cos((l2.longitude - l1.longitude) * p)) /\n          2;\n  return 12742 * asin(sqrt(a));\n}\n</code></pre>\n'}, {'answer_id': 59656546, 'author': 'Oleg Medvedyev', 'author_id': 3044692, 'author_profile': 'https://Stackoverflow.com/users/3044692', 'pm_score': 2, 'selected': False, 'text': '<p>As this is the most popular discussion of the topic I\'ll add my experience from late 2019-early 2020 here. To add to the existing answers - my focus was to find an accurate AND fast (i.e. vectorized) solution.</p>\n<p>Let\'s start with what is mostly used by answers here - the Haversine approach. It is trivial to vectorize, see example in python below:</p>\n<pre><code>def haversine(lat1, lon1, lat2, lon2):\n    &quot;&quot;&quot;\n    Calculate the great circle distance between two points\n    on the earth (specified in decimal degrees)\n\n    All args must be of equal length.\n    Distances are in meters.\n    \n    Ref:\n    https://stackoverflow.com/questions/29545704/fast-haversine-approximation-python-pandas\n    https://ipython.readthedocs.io/en/stable/interactive/magics.html\n    &quot;&quot;&quot;\n    Radius = 6.371e6\n    lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])\n\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n\n    a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2\n\n    c = 2 * np.arcsin(np.sqrt(a))\n    s12 = Radius * c\n    \n    # initial azimuth in degrees\n    y = np.sin(lon2-lon1) * np.cos(lat2)\n    x = np.cos(lat1)*np.sin(lat2) - np.sin(lat1)*np.cos(lat2)*np.cos(dlon)\n    azi1 = np.arctan2(y, x)*180./math.pi\n\n    return {\'s12\':s12, \'azi1\': azi1}\n</code></pre>\n<p>Accuracy-wise, it is least accurate. Wikipedia states 0.5% of relative deviation on average without any sources. My experiments show less of a deviation. Below is the comparison ran on 100,000 random points vs my library, which should be accurate to millimeter levels:</p>\n<pre><code>np.random.seed(42)\nlats1 = np.random.uniform(-90,90,100000)\nlons1 = np.random.uniform(-180,180,100000)\nlats2 = np.random.uniform(-90,90,100000)\nlons2 = np.random.uniform(-180,180,100000)\nr1 = inverse(lats1, lons1, lats2, lons2)\nr2 = haversine(lats1, lons1, lats2, lons2)\nprint(&quot;Max absolute error: {:4.2f}m&quot;.format(np.max(r1[\'s12\']-r2[\'s12\'])))\nprint(&quot;Mean absolute error: {:4.2f}m&quot;.format(np.mean(r1[\'s12\']-r2[\'s12\'])))\nprint(&quot;Max relative error: {:4.2f}%&quot;.format(np.max((r2[\'s12\']/r1[\'s12\']-1)*100)))\nprint(&quot;Mean relative error: {:4.2f}%&quot;.format(np.mean((r2[\'s12\']/r1[\'s12\']-1)*100)))\n</code></pre>\n<p>Output:</p>\n<pre><code>Max absolute error: 26671.47m\nMean absolute error: -2499.84m\nMax relative error: 0.55%\nMean relative error: -0.02%\n</code></pre>\n<p>So on average 2.5km deviation on 100,000 random pairs of coordinates, which may be good for majority of cases.</p>\n<p>Next option is Vincenty\'s formulae which is accurate up to millimeters, depending on convergence criteria and can be vectorized as well. It does have the issue with convergence near antipodal points. You can make it converge at those points by relaxing convergence criteria, but accuracy drops to 0.25% and more. Outside of antipodal points Vincenty will provide results close to Geographiclib within relative error of less than 1.e-6 on average.</p>\n<p>Geographiclib, mentioned here, is really the current golden standard. It has several implementations and fairly fast, especially if you are using C++ version.</p>\n<p>Now, if you are planning to use Python for anything above 10k points I\'d suggest to consider my vectorized implementation. I created a <a href="https://pypi.org/project/geovectorslib/" rel="nofollow noreferrer">geovectorslib</a> library with vectorized Vincenty routine for my own needs, which uses Geographiclib as fallback for near antipodal points. Below is the comparison vs Geographiclib for 100k points. As you can see it provides up to <strong>20x improvement for inverse and 100x for direct</strong> methods for 100k points and the gap will grow with number of points. Accuracy-wise it will be within 1.e-5 rtol of Georgraphiclib.</p>\n<pre><code>Direct method for 100,000 points\n94.9 ms ± 25 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n9.79 s ± 1.4 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nInverse method for 100,000 points\n1.5 s ± 504 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n24.2 s ± 3.91 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n'}, {'answer_id': 59682648, 'author': 'WapShivam', 'author_id': 9629819, 'author_profile': 'https://Stackoverflow.com/users/9629819', 'pm_score': 1, 'selected': False, 'text': '<p>You can calculate it by using Haversine formula which is:</p>\n\n<pre><code>a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)\nc = 2 ⋅ atan2( √a, √(1−a) )\nd = R ⋅ c\n</code></pre>\n\n<p>An example to calculate distance between two points is given below</p>\n\n<p>Suppose i have to calculate distance between New Delhi to London, so how can i use this formula :</p>\n\n<pre><code>New delhi co-ordinates= 28.7041° N, 77.1025° E\nLondon co-ordinates= 51.5074° N, 0.1278° W\n\nvar R = 6371e3; // metres\nvar φ1 = 28.7041.toRadians();\nvar φ2 = 51.5074.toRadians();\nvar Δφ = (51.5074-28.7041).toRadians();\nvar Δλ = (0.1278-77.1025).toRadians();\n\nvar a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +\n        Math.cos(φ1) * Math.cos(φ2) *\n        Math.sin(Δλ/2) * Math.sin(Δλ/2);\nvar c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n\nvar d = R * c; // metres\nd = d/1000; // km\n</code></pre>\n'}, {'answer_id': 60159168, 'author': 'Korayem', 'author_id': 80434, 'author_profile': 'https://Stackoverflow.com/users/80434', 'pm_score': 2, 'selected': False, 'text': '<p>For those looking for an Excel formula based on WGS-84 &amp; GRS-80 standards:</p>\n\n<pre><code>=ACOS(COS(RADIANS(90-Lat1))*COS(RADIANS(90-Lat2))+SIN(RADIANS(90-Lat1))*SIN(RADIANS(90-Lat2))*COS(RADIANS(Long1-Long2)))*6371\n</code></pre>\n\n<p><a href="https://bluemm.blogspot.com/2007/01/excel-formula-to-calculate-distance.html" rel="nofollow noreferrer">Source</a></p>\n'}, {'answer_id': 62139010, 'author': 'Kristian K', 'author_id': 13505403, 'author_profile': 'https://Stackoverflow.com/users/13505403', 'pm_score': 1, 'selected': False, 'text': '<p>The functions needed for an accurate calculation of distance between lat-long points are complex, and the pitfalls are many. I would not recomend haversine or other spherical solutions due to the big inaccuracies (the earth is not a perfect sphere). The <a href="https://en.wikipedia.org/wiki/Vincenty%27s_formulae" rel="nofollow noreferrer">vincenty formula</a> is better, but will in some cases throw errors, even when coded correctly.</p>\n\n<p>Instead of coding the functions yourself I suggest using <a href="https://geopy.readthedocs.io/en/stable/" rel="nofollow noreferrer">geopy</a> which have implemented the very accurate <a href="https://geographiclib.sourceforge.io/html/python/" rel="nofollow noreferrer">geographiclib</a> for distance calculations (<a href="https://link.springer.com/content/pdf/10.1007/s00190-012-0578-z.pdf" rel="nofollow noreferrer">paper from author</a>). </p>\n\n<pre><code>#pip install geopy\nfrom geopy.distance import geodesic\nNY = [40.71278,-74.00594]\nBeijing = [39.90421,116.40739]\nprint("WGS84: ",geodesic(NY, Beijing).km) #WGS84 is Standard\nprint("Intl24: ",geodesic(NY, Beijing, ellipsoid=\'Intl 1924\').km) #geopy includes different ellipsoids\nprint("Custom ellipsoid: ",geodesic(NY, Beijing, ellipsoid=(6377., 6356., 1 / 297.)).km) #custom ellipsoid\n\n#supported ellipsoids:\n#model             major (km)   minor (km)     flattening\n#\'WGS-84\':        (6378.137,    6356.7523142,  1 / 298.257223563)\n#\'GRS-80\':        (6378.137,    6356.7523141,  1 / 298.257222101)\n#\'Airy (1830)\':   (6377.563396, 6356.256909,   1 / 299.3249646)\n#\'Intl 1924\':     (6378.388,    6356.911946,   1 / 297.0)\n#\'Clarke (1880)\': (6378.249145, 6356.51486955, 1 / 293.465)\n#\'GRS-67\':        (6378.1600,   6356.774719,   1 / 298.25)\n</code></pre>\n\n<p>The only drawback with this library is that it doesn\'t support vectorized calculations.\nFor vectorized calculations you can use the new <a href="https://pypi.org/project/geovectorslib/" rel="nofollow noreferrer">geovectorslib</a>.</p>\n\n<pre><code>#pip install geovectorslib\nfrom geovectorslib import inverse\nprint(inverse(lats1,lons1,lats2,lons2)[\'s12\'])\n</code></pre>\n\n<p>lats and lons are numpy arrays. Geovectorslib is very accurate and extremly fast! I haven\'t found a solution for changing ellipsoids though. The WGS84 ellipsoid is used as standard, which is the best choice for most uses.</p>\n'}, {'answer_id': 64214020, 'author': 'sourav karwa', 'author_id': 5022656, 'author_profile': 'https://Stackoverflow.com/users/5022656', 'pm_score': 2, 'selected': False, 'text': '<p>I made a custom function in R to calculate haversine distance(km) between two spatial points using functions available in R base package.</p>\n<pre><code>custom_hav_dist &lt;- function(lat1, lon1, lat2, lon2) {\nR &lt;- 6371\nRadian_factor &lt;- 0.0174533\nlat_1 &lt;- (90-lat1)*Radian_factor\nlat_2 &lt;- (90-lat2)*Radian_factor\ndiff_long &lt;-(lon1-lon2)*Radian_factor\n\ndistance_in_km &lt;- 6371*acos((cos(lat_1)*cos(lat_2))+ \n                 (sin(lat_1)*sin(lat_2)*cos(diff_long)))\nrm(lat1, lon1, lat2, lon2)\nreturn(distance_in_km)\n}\n</code></pre>\n<p>Sample output</p>\n<pre><code>custom_hav_dist(50.31,19.08,54.14,19.39)\n[1] 426.3987\n</code></pre>\n<p>PS: To calculate distances in miles, substitute R in function (6371) with 3958.756 (and for nautical miles, use 3440.065).</p>\n'}, {'answer_id': 64696900, 'author': 'Irfan wani', 'author_id': 13789135, 'author_profile': 'https://Stackoverflow.com/users/13789135', 'pm_score': 1, 'selected': False, 'text': "<p>If you are using python;\npip install geopy</p>\n<pre><code>from geopy.distance import geodesic\n\n\norigin = (30.172705, 31.526725)  # (latitude, longitude) don't confuse\ndestination = (30.288281, 31.732326)\n\nprint(geodesic(origin, destination).meters)  # 23576.805481751613\nprint(geodesic(origin, destination).kilometers)  # 23.576805481751613\nprint(geodesic(origin, destination).miles)  # 14.64994773134371\n</code></pre>\n"}, {'answer_id': 65109214, 'author': 'Renato Probst', 'author_id': 1713345, 'author_profile': 'https://Stackoverflow.com/users/1713345', 'pm_score': 2, 'selected': False, 'text': '<p>If you want the driving distance/route (posting it here because this is the first result for the distance between two points on google but for most people the driving distance is more useful), you can use <a href="https://developers.google.com/maps/documentation/javascript/distancematrix" rel="nofollow noreferrer">Google Maps Distance Matrix Service</a>:</p>\n<pre><code>getDrivingDistanceBetweenTwoLatLong(origin, destination) {\n\n return new Observable(subscriber =&gt; {\n  let service = new google.maps.DistanceMatrixService();\n  service.getDistanceMatrix(\n    {\n      origins: [new google.maps.LatLng(origin.lat, origin.long)],\n      destinations: [new google.maps.LatLng(destination.lat, destination.long)],\n      travelMode: \'DRIVING\'\n    }, (response, status) =&gt; {\n      if (status !== google.maps.DistanceMatrixStatus.OK) {\n        console.log(\'Error:\', status);\n        subscriber.error({error: status, status: status});\n      } else {\n        console.log(response);\n        try {\n          let valueInMeters = response.rows[0].elements[0].distance.value;\n          let valueInKms = valueInMeters / 1000;\n          subscriber.next(valueInKms);\n          subscriber.complete();\n        }\n       catch(error) {\n        subscriber.error({error: error, status: status});\n       }\n      }\n    });\n});\n}\n</code></pre>\n'}, {'answer_id': 66994120, 'author': 'Anurag', 'author_id': 10665583, 'author_profile': 'https://Stackoverflow.com/users/10665583', 'pm_score': 0, 'selected': False, 'text': '<pre><code>function distance($lat1, $lon1, $lat2, $lon2) { \n    $pi80 = M_PI / 180; \n    $lat1 *= $pi80; $lon1 *= $pi80; $lat2 *= $pi80; $lon2 *= $pi80; \n    $dlat = $lat2 - $lat1; \n    $dlon = $lon2 - $lon1; \n    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);  \n    $km = 6372.797 * 2 * atan2(sqrt($a), sqrt(1 - $a)); \n    return $km; \n}\n</code></pre>\n'}, {'answer_id': 67357990, 'author': 'Aaron Lelevier', 'author_id': 1913888, 'author_profile': 'https://Stackoverflow.com/users/1913888', 'pm_score': 1, 'selected': False, 'text': '<p>Here is the Erlang implementation</p>\n<pre class="lang-erlang prettyprint-override"><code>lat_lng({Lat1, Lon1}=_Point1, {Lat2, Lon2}=_Point2) -&gt;\n  P = math:pi() / 180,\n  R = 6371, % Radius of Earth in KM\n  A = 0.5 - math:cos((Lat2 - Lat1) * P) / 2 +\n    math:cos(Lat1 * P) * math:cos(Lat2 * P) * (1 - math:cos((Lon2 - Lon1) * P))/2,\n  R * 2 * math:asin(math:sqrt(A)).\n</code></pre>\n'}, {'answer_id': 68985288, 'author': 'Arthur Ronconi', 'author_id': 2272598, 'author_profile': 'https://Stackoverflow.com/users/2272598', 'pm_score': 2, 'selected': False, 'text': '<p>You could use a module like geolib too:</p>\n<p>How to install:</p>\n<pre><code>$ npm install geolib\n</code></pre>\n<p>How to use:</p>\n<pre class="lang-js prettyprint-override"><code>import { getDistance } from \'geolib\'\n\nconst distance = getDistance(\n    { latitude: 51.5103, longitude: 7.49347 },\n    { latitude: &quot;51° 31\' N&quot;, longitude: &quot;7° 28\' E&quot; }\n)\n\nconsole.log(distance)\n</code></pre>\n<p>Documentation:\n<a href="https://www.npmjs.com/package/geolib" rel="nofollow noreferrer">https://www.npmjs.com/package/geolib</a></p>\n'}, {'answer_id': 70532052, 'author': 'Remis Haroon - رامز', 'author_id': 1843011, 'author_profile': 'https://Stackoverflow.com/users/1843011', 'pm_score': 0, 'selected': False, 'text': "<p>Here's a Scala implementation:</p>\n<pre><code>  def calculateHaversineDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double = {\n    val long2 = lon2 * math.Pi / 180\n    val lat2 = lat2 * math.Pi / 180\n    val long1 = lon1 * math.Pi / 180\n    val lat1 = lat1 * math.Pi / 180\n\n    val dlon = long2 - long1\n    val dlat = lat2 - lat1\n    val a = math.pow(math.sin(dlat / 2), 2) + math.cos(lat1) * math.cos(lat2) * math.pow(math.sin(dlon / 2), 2)\n    val c = 2 * math.atan2(Math.sqrt(a), math.sqrt(1 - a))\n    val haversineDistance = 3961 * c // 3961 = radius of earth in miles\n    haversineDistance\n  }\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/27928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1456/']