How to calculate the distance between two latitude-longitude points in Python

1 Answer

0 votes
import math

# ------------------------------------------------------------
# Convert degrees to radians
# ------------------------------------------------------------
def deg_to_rad(deg: float) -> float:
    return deg * math.pi / 180.0

# ------------------------------------------------------------
# Compute the great-circle distance between two points on Earth
# using the Haversine formula.
# lat1, lon1, lat2, lon2 are in degrees.
# The result is returned in kilometers.
# ------------------------------------------------------------
def haversine(lat1: float, lon1: float,
              lat2: float, lon2: float) -> float:

    # Earth's mean radius in kilometers
    R = 6371.0

    # Convert all angles to radians
    rlat1 = deg_to_rad(lat1)
    rlon1 = deg_to_rad(lon1)
    rlat2 = deg_to_rad(lat2)
    rlon2 = deg_to_rad(lon2)

    # Differences
    dlat = rlat2 - rlat1
    dlon = rlon2 - rlon1

    # Haversine formula
    # a is the Haversine of the central angle between the two points.
    a = math.sin(dlat / 2)**2 + \
        math.cos(rlat1) * math.cos(rlat2) * math.sin(dlon / 2)**2

    # c is the central angle between the two points on the Earth’s surface.
    c = 2 * math.asin(math.sqrt(a))

    # Final distance
    return R * c

# ------------------------------------------------------------
# Main 
# ------------------------------------------------------------
if __name__ == "__main__":

    # Example coordinates:
    # Austin, Texas
    lat1 = 30.2672
    lon1 = -97.7431

    # Houston, Texas
    lat2 = 29.7604
    lon2 = -95.3698

    distance_km = haversine(lat1, lon1, lat2, lon2)

    # Convert kilometers to miles
    distance_miles = distance_km * 0.621371

    print(f"Distance: {distance_km:.3f} km")
    print(f"Distance: {distance_miles:.3f} miles")



"""
run:

Distance: 235.352 km
Distance: 146.241 miles

"""

 



answered Aug 7 by avibootz

Related questions

...