Haversine Formula in Python (Bearing and Distance between two GPS points)

后端 未结 10 1767
死守一世寂寞
死守一世寂寞 2020-11-22 09:47

Problem

I would like to know how to get the distance and bearing between 2 GPS points. I have researched on the haversine formula. Someone told me

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 10:25

    Most of these answers are "rounding" the radius of the earth. If you check these against other distance calculators (such as geopy), these functions will be off.

    This works well:

    from math import radians, cos, sin, asin, sqrt
    
    def haversine(lat1, lon1, lat2, lon2):
    
          R = 3959.87433 # this is in miles.  For Earth radius in kilometers use 6372.8 km
    
          dLat = radians(lat2 - lat1)
          dLon = radians(lon2 - lon1)
          lat1 = radians(lat1)
          lat2 = radians(lat2)
    
          a = sin(dLat/2)**2 + cos(lat1)*cos(lat2)*sin(dLon/2)**2
          c = 2*asin(sqrt(a))
    
          return R * c
    
    # Usage
    lon1 = -103.548851
    lat1 = 32.0004311
    lon2 = -103.6041946
    lat2 = 33.374939
    
    print(haversine(lat1, lon1, lat2, lon2))
    

提交回复
热议问题