Home > Back-end >  How do I get distance in python or c#?
How do I get distance in python or c#?

Time:10-02

I want to be able to calculate the distance between two locations. So I have bill, his longitude and latitude is 5,6. And I have bob, his longitude and latitude is 9,2. Is there anything in c# or python that will make me able to get the distance in miles?

CodePudding user response:

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

enter image description here

`where φ is latitude (in radians), λ is longitude (in radians) , 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.
    lon1 = radians(lon1)
    lon2 = radians(lon2)
    lat1 = radians(lat1)
    lat2 = radians(lat2)
      
    # 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

https://www.geeksforgeeks.org/program-distance-two-points-earth/#:~:text=For this divide the values,is the radius of Earth.

https://www.youtube.com/watch?v=nsVsdHeTXIE&ab_channel=Qarbyte

CodePudding user response:

You probably have to implement it yourself - look here or just search 'distance between two coordinates':

https://www.movable-type.co.uk/scripts/latlong.html

  • Related