0
Follow
0
View

# How do I get distance in python or c#?

ZOOOOM 注册会员
2023-01-25 02:52

## Distance between any 2 points on the surface shape (Earth) is calculated using the `Haversine formula`

1-First, convert the latitude and longitude values from decimal degrees to radians by dividing the values of longitude and latitude of both the points by 180/pi `(pi=22/7)`

Value of Latitude in Radians = lat / (180/pi) Value of Longitude in Radians = long / (180/pi)

2- after converting lat, long to Radians for the 2 points you should have now
`(lat1_r,long1_r)` ,`(lat2_r,long2_r)`

3-Calculate distance now by `d = 3963.0 * arccos[(sin(lat1_r) * sin(lat2_r)) + cos(lat1_r) * cos(lat2_r) * cos(long2_r– long1_r)]`

4- this distance will be in miles, to get it in km

`d in kilometers = 1.609344 * d in miles`

5- write the logic in any language you like

## Easy Haversine formula with code in Python

1-after converting lat,long to Radians for the 2 points you should now have
`(lat1_r,long1_r)` ,`(lat2_r,long2_r)`

2- we need to get `a`,`c`, `d` using following formulas

`where φ is latitude , λ is longitude , R is earth’s radius (mean radius = 6,371km);

### Haversine formula Code in Python

``````from math import radians, cos, sin, asin, sqrt ,atan2
def distance(lat1, lat2, lon1, lon2):

# The math module contains a function named
# radians which converts from degrees to radians.

# Haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2

c = 2 * asin(sqrt(a))
# you can use atan2 instead of asin and get same result
# c = 2 * atan2(sqrt(a), sqrt(1-a))

# Radius of earth in kilometers. Use 3956 for miles
r = 6371

# calculate the result
return(c * r)
``````

### if you believe the earth is flat then you can use `euclidean distance` :D

x is latitude and y is longitude (x1,y1) the first point (x2,y2) is the second point, so you can build your own method in any language

`d=√((x2 – x1)² + (y2 – y1)²)`.

References

duochi001 注册会员

Publish Time
2023-01-25 02:52
Update Time
2023-01-25 02:52