Home > Backend Development > Python Tutorial > How Can I Accurately Calculate GPS Distance and Bearing Using the Haversine Formula?

How Can I Accurately Calculate GPS Distance and Bearing Using the Haversine Formula?

Mary-Kate Olsen
Release: 2024-12-02 08:42:11
Original
944 people have browsed it

How Can I Accurately Calculate GPS Distance and Bearing Using the Haversine Formula?

Haversine Formula for GPS Calculations: Distance and Bearing

Problem:

Calculating the distance and bearing between two GPS points often involves utilizing the Haversine distance formula. However, issues can arise when obtaining the correct bearing, particularly if negative values are produced.

Solution:

To calculate the distance, the Haversine formula can be employed:

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

def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance in kilometers 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. Determines return value units.
    return c * r
Copy after login

To determine the bearing, adjust the Bearing variable as follows:

Bearing = atan2(sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(lon2-lon1))
Bearing = degrees(Bearing)
Copy after login

This modification ensures that the bearing lies between 0 and 360 degrees.

The above is the detailed content of How Can I Accurately Calculate GPS Distance and Bearing Using the Haversine Formula?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template