Haversine Distance Calculation with GeoPandas

  • Share this:

Code introduction


This function calculates the distance between two geographic coordinates using the Haversine formula and the GeoPandas library.


Technology Stack : GeoPandas, Numpy

Code Type : Function

Code Difficulty : Intermediate


                
                    
def calculate_distance_between_points(geometry1, geometry2):
    """
    Calculate the distance between two geometries using the Haversine formula.
    """
    from geopandas import GeoDataFrame
    import numpy as np

    def haversine(lon1, lat1, lon2, lat2):
        """
        Calculate the great circle distance between two points 
        on the earth (specified in decimal degrees)
        """
        # 将十进制度数转换为弧度
        lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])

        # haversine公式
        dlon = lon2 - lon1 
        dlat = lat2 - lat1 
        a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
        c = 2 * np.arcsin(np.sqrt(a)) 
        r = 6371  # 地球平均半径,单位为公里
        return c * r

    # 将几何对象转换为十进制度数
    gdf1 = GeoDataFrame([geometry1])
    gdf2 = GeoDataFrame([geometry2])
    gdf1['lon'] = gdf1.geometry.x
    gdf1['lat'] = gdf1.geometry.y
    gdf2['lon'] = gdf2.geometry.x
    gdf2['lat'] = gdf2.geometry.y

    # 计算距离
    distance = haversine(gdf1['lon'].iloc[0], gdf1['lat'].iloc[0], gdf2['lon'].iloc[0], gdf2['lat'].iloc[0])
    return distance