math - How to convert latitude or longitude to meters? - Stack Overflow
Calculate distance in meters when you know longitude and latitude in java - Stack Overflow
calculate distance using latitude and longitude excel
python - Getting distance between two points based on latitude/longitude - Stack Overflow
How accurate is this Distance Calculator?
How is distance calculated between coordinates?
How do I calculate the distance between two points with longitude and latitude?
To calculate the distance between two points given longitude and latitude coordinates:
-
Write down each point's coordinates in degrees-only format. We'll call θ and φ to their respective latitude and longitude components.
-
Input them in the haversine distance formula:
d = 2R × sin⁻¹(√[sin²((θ₂ - θ₁)/2) + cosθ₁ × cosθ₂ × sin²((φ₂ - φ₁)/2)]).
where:
- (θ₁, φ₁) and (θ₂, φ₂) – Each point's coordinates;
- R – Earth's radius; and
- d – Great circle or 'as the crow flies' distance between the points.
Videos
Here is a javascript function:
Copyfunction measure(lat1, lon1, lat2, lon2){ // generally used geo measurement function
var R = 6378.137; // Radius of earth in KM
var dLat = lat2 * Math.PI / 180 - lat1 * Math.PI / 180;
var dLon = lon2 * Math.PI / 180 - lon1 * 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;
return d * 1000; // meters
}
Explanation: https://en.wikipedia.org/wiki/Haversine_formula
The haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes.
Given you're looking for a simple formula, this is probably the simplest way to do it, assuming that the Earth is a sphere with a circumference of 40075 km.
Length in km of 1° of latitude = always 111.32 km
Length in km of 1° of longitude = 40075 km * cos( latitude ) / 360
Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.
Implementation goes like this:
import org.gavaghan.geodesy.*;
...
GeodeticCalculator geoCalc = new GeodeticCalculator();
Ellipsoid reference = Ellipsoid.WGS84;
GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A
GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B
double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B
The resulting distance is in meters.
The Vincenty distance is now deprecated since GeoPy version 1.13 - you should use geopy.distance.distance() instead!
Some previous answers were based on the haversine formula, which assumes the earth is a sphere, which results in errors of up to about 0.5% (according to help(geopy.distance)). The Vincenty distance uses more accurate ellipsoidal models, such as WGS-84, and is implemented in geopy. For example,
Copyimport geopy.distance
coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)
print(geopy.distance.geodesic(coords_1, coords_2).km)
will print the distance of 279.352901604 kilometers using the default ellipsoid WGS-84. (You can also choose .miles or one of several other distance units.)
Just as a note, if you just need a quick and easy way of finding the distance between two points, I strongly recommend using the approach described in Kurt's answer instead of reimplementing Haversine—see his post for rationale.
This answer focuses just on answering the specific bug the OP ran into.
It's because in Python, all the trigonometry functions use radians, not degrees.
You can either convert the numbers manually to radians, or use the radians function from the math module:
Copyfrom math import sin, cos, sqrt, atan2, radians
# Approximate radius of earth in km
R = 6373.0
lat1 = radians(52.2296756)
lon1 = radians(21.0122287)
lat2 = radians(52.406374)
lon2 = radians(16.9251681)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
print("Result: ", distance)
print("Should be: ", 278.546, "km")
The distance is now returning the correct value of 278.545589351 km.
Loading the geosphere package you can use a number of different functions
library(geosphere)
distm(c(lon1, lat1), c(lon2, lat2), fun = distHaversine)
Also:
distHaversine()
distMeeus()
distRhumb()
distVincentyEllipsoid()
distVincentySphere()
...
Agree with @PereG on answer above, but think that the order of latitude and longitude is the other way around: lon, lat. This will affect your results for distance matrix. So correct is:
library(geosphere)
distm (c(lon1, lat1), c(lon2, lat2), fun = distHaversine)
Source: ftp://cran.r-project.org/pub/R/web/packages/geosphere/geosphere.pdf
The tool seems to be just calculating the Euclidean distance between the two points (the square root of the sum of the squared differences between the coordinates). This doesn't make any sense for latitudes and longitudes, which are not coordinates in a Cartesian coordinate system. Not only is this number not a meaningful distance, but it no longer contains the information required to reconstruct a distance from it, so you won't be able to calculate anything meaningful from it; you need to go back to the latitudes and longitudes themselves.
To calculate distances between points given by latitudes and longitudes precisely, you need to know which geoid was used as a reference in specifying them. But since you only want to get within 95% of the answer, you can safely assume that the Earth is a sphere.
There are two possible meanings for "the distance between two points" on a sphere. You can take the Euclidean distance between the two points (the actual points, not their latitude/longitude coordinates like your tool does), or you can take distance along the shortest curve along the surface of the Earth. Again, if you only want to get to within 95% of the answer and the distances are as small as in your example, the difference is negligble, so you can take the Euclidean distance, which is easier to calculate.
To get the Euclidean distance, you can first calculate the Cartesian coordinates of the points from their latitudes and longitudes. Denoting the latitude by $\theta$, the longitude by $\phi$ and the Earth's radius by $R$ (with $R\approx 6371 \mathrm{km}$), these are given by
$$\vec{r}=\left(\begin{array}{c}x\\y\\z\end{array}\right) = \left(\begin{array}{c} R\cos\theta\cos\phi \\ R\cos\theta\sin\phi \\ R\sin\theta \end{array}\right)\;. $$
Then you get the distance between them using
$$d(\vec{r_1},\vec{r_2})=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2+(z_2-z_1)^2}\;.$$
Since you seem to have small distances and aren't interested in precision, you can simplify this by expanding the trigonometric functions around one of the points, or, for greater precision, around the midpoint $\theta=(\theta_1+\theta_2)/2$, $\phi=(\phi_1+\phi_2)/2$:
$$\vec{r_2}-\vec{r_1}\approx R\left(\begin{array}{c} \sin\theta\cos\phi(\theta_2-\theta_1)-\cos\theta\sin\phi(\phi_2-\phi_1) \\ \sin\theta\sin\phi(\theta_2-\theta_1)+\cos\theta\cos\phi(\phi_2-\phi_1) \\ \cos\theta(\theta_2-\theta_1) \end{array}\right)\;, $$
$${}$$
$$\lvert\vec{r}_2-\vec{r}_1\rvert\approx R\sqrt{(\theta_2-\theta_1)^2 + \cos^2\theta(\phi_2-\phi_1)^2}\;.$$
If the distances are small, you can use the linearized version: $\Delta x=R \cos(\theta)\Delta \phi, \Delta y=R \Delta \theta$, where $x$ is east-west distance, $\theta$ is latitude (measured with zero at the equator), $y$ is north-south distance, and $\phi$ is longitude. Then the distance is $d=\sqrt{\Delta x^2+ \Delta y^2}$ in whatever units you used for $R$.
You can calculate distance between flat coordinates in, say, meters by using geopy package or Vincenty's formula, pasting coordinates directly. Suppose the result is d meters. Then the total distance travelled is sqrt(d**2 + h**2) where h is the change in elevation in meters.
I used the solution provided by John Moutafis but I didn't get a right answer.The formula needs some corrections. You will get the conversion of coordinates from Polar to Cartesian (x, y, z) at http://electron9.phys.utk.edu/vectors/3dcoordinates.htm. Use the above formula to convert spherical coordinates(Polar) to Cartesian and calculate Euclidean distance.
I used the following c# in a console app. Considering following dummy lat long
double lat_1 = 18.457793 * (Math.PI / 180);
double lon_1 = 73.3951930277778 *(Math.PI/180);
double alt_1 = 270.146;
double lat_2 = 18.4581253333333 * (Math.PI / 180);
double lon_2 = 73.3963755277778 * (Math.PI / 180);
double alt_2 = 317.473;
const Double r = 6376.5 *1000; // Radius of Earth in metres
double x_1 = r * Math.Sin(lon_1) * Math.Cos(lat_1);
double y_1 = r * Math.Sin(lon_1) * Math.Sin(lat_1);
double z_1 = r * Math.Cos(lon_1);
double x_2 = r * Math.Sin(lon_2) * Math.Cos(lat_2);
double y_2 = r * Math.Sin(lon_2) * Math.Sin(lat_2);
double z_2 = r * Math.Cos(lon_2);
double dist = Math.Sqrt((x_2 - x_1) * (x_2 - x_1) + (y_2 - y_1) *
(y_2 - y_1) + (z_2 - z_1) * (z_2 - z_1));
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)
}
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 runs 2 times faster than the most upvoted answer.
function distance(lat1, lon1, lat2, lon2) {
const r = 6371; // km
const p = Math.PI / 180;
const a = 0.5 - Math.cos((lat2 - lat1) * p) / 2
+ Math.cos(lat1 * p) * Math.cos(lat2 * p) *
(1 - Math.cos((lon2 - lon1) * p)) / 2;
return 2 * r * Math.asin(Math.sqrt(a));
}
You can play with my jsPerf and see the results here.
Recently I needed to do the same in python, so here is a python implementation:
from math import cos, asin, sqrt, pi
def distance(lat1, lon1, lat2, lon2):
r = 6371 # km
p = pi / 180
a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2
return 2 * r * asin(sqrt(a))
And for the sake of completeness: Haversine on Wikipedia.