Formulas to Calculate Geo Proximity
The Law of Cosines and the Haversine Formula will give identical results assuming a machine with infinite precision. The Haversine formula is more robust to floating point errors. However, today's machines have double precision of the order of 15 significant figures, and the law of cosines may work just fine for you. Both these formulas assume spherical earth, whereas Vicenty's iterative solution (most accurate) assumes ellipsoidal earth (in reality the earth is not even an ellipsoid - it is a geoid). Some references:
http://www.movable-type.co.uk/scripts/gis-faq-5.1.html
It gets better: note the latitude to be used in the law of cosines as well as the Haversine is the geocentric latitude, which is different from geodetic latitude. For a sphere, these two are the same.
Which one is fastest to compute?
In order from fastest to slowest are: law of cosines (5 trig. calls) -> haversine (involves sqrt) -> Vicenty (have to solve this iteratively in a for loop)
Which one is most accurate?
Vicenty.
Which one is best when speed and accuracy are both considered?
If your problem domain is such that for the distances you are trying to calculate, the earth can be considered as flat, then you can work out (I am not going to give details) a formula of the form x = kx * difference in longitude, y = ky * difference in latitude. Then distance = sqrt(dxdx + dydy). If your problem domain is such that it can be solved with distance squared, then you won't have to take sqrt, and this formula will be as fast as you get possibly get. It has the added advantage that you can calculate the vector distance - x is distance in east direction, and y is distance in the north direction.
Otherwise, experiment with the 3 and choose what works best in your situation.
Calculate distance between two latitude-longitude points? (Haversine formula)
This link might be helpful to you, as it details the use of the Haversine formula to calculate the distance.
Excerpt:
This script [in Javascript] calculates great-circle distances between the two points –
that is, the shortest distance over the earth’s surface – using the
‘Haversine’ formula.
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(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; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
Calculate distance between 2 GPS coordinates
Calculate the distance between two coordinates by latitude and longitude, including a Javascript implementation.
West and South locations are negative.
Remember minutes and seconds are out of 60 so S31 30' is -31.50 degrees.
Don't forget to convert degrees to radians. Many languages have this function. Or its a simple calculation: radians = degrees * PI / 180
.
function degreesToRadians(degrees) {
return degrees * Math.PI / 180;
}
function distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {
var earthRadiusKm = 6371;
var dLat = degreesToRadians(lat2-lat1);
var dLon = degreesToRadians(lon2-lon1);
lat1 = degreesToRadians(lat1);
lat2 = degreesToRadians(lat2);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return earthRadiusKm * c;
}
Here are some examples of usage:
distanceInKmBetweenEarthCoordinates(0,0,0,0) // Distance between same
// points should be 0
0
distanceInKmBetweenEarthCoordinates(51.5, 0, 38.8, -77.1) // From London
// to Arlington
5918.185064088764
What formula to use to calculate a small distance
See this page. It contains great-circle distance calculation functions for various programming languages.
In PHP:
function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {
$earth_radius = 6371; // In the unit you want the result in.
$dLat = deg2rad($latitude2 - $latitude1);
$dLon = deg2rad($longitude2 - $longitude1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * asin(sqrt($a));
$d = $earth_radius * $c;
return $d;
}
Function to calculate distance between two coordinates
What you're using is called the haversine formula, which calculates the distance between two points on a sphere as the crow flies. The Google Maps link you provided shows the distance as 2.2 km because it's not a straight line.
Wolfram Alpha is a great resource for doing geographic calculations, and also shows a distance of 1.652 km between these two points.
If you're looking for straight-line distance (as the crow files), your function is working correctly. If what you want is driving distance (or biking distance or public transportation distance or walking distance), you'll have to use a mapping API (Google or Bing being the most popular) to get the appropriate route, which will include the distance.
Incidentally, the Google Maps API provides a packaged method for spherical distance, in its google.maps.geometry.spherical
namespace (look for computeDistanceBetween
). It's probably better than rolling your own (for starters, it uses a more precise value for the Earth's radius).
For the picky among us, when I say "straight-line distance", I'm referring to a "straight line on a sphere", which is actually a curved line (i.e. the great-circle distance), of course.
Distance between 2 geocodes
Use an approximation of the earth and the Haversine formula. You can get a javascript version on the following url, which you can translate to your language of choice:
http://www.movable-type.co.uk/scripts/latlong.html
Here is another way: http://escience.anu.edu.au/project/04S2/SE/3DVOT/3DVOT/pHatTrack_Application/Source_code/pHatTrack/Converter.java
Calculating geospatial distance with radians
It's correct. Although I feel a little shame posting this as an answer :)
How to get distance in few meters between 2 pair of latitude longitude
I have used the Haversine formula in PHP to calculate distance in kms between two geocoordinates:
// Haversine formula
function geoDistance($lon1, $lat1, $lon2, $lat2) {
$R = 6371; // Radius of the earth in km
$dLat = deg2rad($lat2 - $lat1);
$dLon = deg2rad($lon2 - $lon1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * atan2(sqrt($a), sqrt(1-$a));
$d = $R * $c; // Distance in km
return $d;
}
I guess, having enough precision in lon and lat would yield a result that multiplied by 1,000 migth be useful as a measure of distance in meters, right?
According to https://gis.stackexchange.com/questions/8650/measuring-accuracy-of-latitude-and-longitude the fifth decimal place is worth up to 1.1 m: it distinguish trees from each other.
Related Topics
How to Alias a Table in Laravel Eloquent Queries (Or Using Query Builder)
Upload a File Using File_Get_Contents
Can You Add an If Statement in Order By
How to Use Curl Instead of File_Get_Contents
How to Enable PHP's Openssl Extension to Install Composer
Laravel Eloquent Sum of Relation's Column
Send PHP Date to JavaScript Date Format
How to Extract Links and Titles from a .HTML Page
Static' Keyword Inside Function
Get Custom Product Attributes in Woocommerce
Destroy or Unset Session When User Close the Browser Without Clicking on Logout
Mysql_Real_Escape_String VS Addslashes
How to Configure Wamp (Localhost) to Send Email Using Gmail