Home >Backend Development >Python Tutorial >How Does the Haversine Formula Calculate Distance and Bearing Between GPS Points in Python?

How Does the Haversine Formula Calculate Distance and Bearing Between GPS Points in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-01 18:41:10557browse

How Does the Haversine Formula Calculate Distance and Bearing Between GPS Points in Python?

Haversine Formula in Python: Calculating Distance and Bearing Between GPS Points

In the world of navigation, determining the distance and bearing between two GPS points is crucial. The Haversine formula provides a precise way to compute these values using spherical geometry.

Calculating Distance Using the Haversine Formula

To calculate the distance between two GPS points, we need to convert their latitudes and longitudes from decimal degrees to radians. We then apply the 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))
distance = c * r

where dlon and dlat represent the differences in longitude and latitude, a is an intermediate value, and r is the radius of the Earth (6371 kilometers for kilometers or 3956 miles for miles).

Calculating Bearing Using the Haversine Formula

In addition to determining the distance, we can also find the bearing (azimuth) from the first point to the second point using the Haversine formula:

y = sin(dlon) * cos(lat2)
x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon)
bearing = atan2(y, x)

where dlon is the difference in longitude, lat1 and lat2 are the latitudes of the two points, x and y are intermediate values, and bearing represents the azimuth measured in radians from north clockwise.

Python Implementation

Here's a Python implementation of the Haversine formula for calculating distance and bearing:

from math import radians, cos, sin, asin, sqrt

def haversine(lon1, lat1, lon2, lat2):
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    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

    return c * r

The above is the detailed content of How Does the Haversine Formula Calculate Distance and Bearing Between GPS Points in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn