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

后端 未结 10 1603
死守一世寂寞
死守一世寂寞 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:27

    You can solve the negative bearing problem by adding 360°. Unfortunately, this might result in bearings larger than 360° for positive bearings. This is a good candidate for the modulo operator, so all in all you should add the line

    Bearing = (Bearing + 360) % 360
    

    at the end of your method.

    0 讨论(0)
  • 2020-11-22 10:28

    Here's a numpy vectorized implementation of the Haversine Formula given by @Michael Dunn, gives a 10-50 times improvement over large vectors.

    from numpy import radians, cos, sin, arcsin, sqrt
    
    def haversine(lon1, lat1, lon2, lat2):
        """
        Calculate the great circle distance between two points 
        on the earth (specified in decimal degrees)
        """
    
        #Convert decimal degrees to Radians:
        lon1 = np.radians(lon1.values)
        lat1 = np.radians(lat1.values)
        lon2 = np.radians(lon2.values)
        lat2 = np.radians(lat2.values)
    
        #Implementing Haversine Formula: 
        dlon = np.subtract(lon2, lon1)
        dlat = np.subtract(lat2, lat1)
    
        a = np.add(np.power(np.sin(np.divide(dlat, 2)), 2),  
                              np.multiply(np.cos(lat1), 
                                          np.multiply(np.cos(lat2), 
                                                      np.power(np.sin(np.divide(dlon, 2)), 2))))
        c = np.multiply(2, np.arcsin(np.sqrt(a)))
        r = 6371
    
        return c*r
    
    0 讨论(0)
  • 2020-11-22 10:31

    Here's a Python version:

    from math import radians, cos, sin, asin, sqrt
    
    def haversine(lon1, lat1, lon2, lat2):
        """
        Calculate the great circle distance between two points 
        on the earth (specified in decimal degrees)
        """
        # convert decimal degrees to radians 
        lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, 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)) 
        r = 6371 # Radius of earth in kilometers. Use 3956 for miles
        return c * r
    
    0 讨论(0)
  • 2020-11-22 10:33

    You can try the following:

    from haversine import haversine
    haversine((45.7597, 4.8422),(48.8567, 2.3508), unit='mi')
    243.71209416020253
    
    0 讨论(0)
提交回复
热议问题