Home >Backend Development >Python Tutorial >How to Calculate the Distance and Bearing Between Two GPS Points Using Python's Haversine Formula?
How to Calculate Bearing and Distance Between Two GPS Points Using Haversine Formula in Python
The Haversine formula is a mathematical equation used to calculate the great-circle distance between two points on a sphere. In the context of GPS, this formula can be employed to determine both the distance and bearing between two GPS coordinates.
Step 1: Defining the Function
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
Step 2: Calculation
start_lon, start_lat = -1.7297222222222221, 53.32055555555556 bearing, distance = 96.02166666666666, 2 end_lon, end_lat = -1.6997222222222223, 53.31861111111111 distance_calculated = haversine(start_lon, start_lat, end_lon, end_lat) print("Distance:", distance_calculated)
Output:
Distance: 2.0000054199729084
In this example, the calculated distance matches the expected value of 2 kilometers.
Note:
The above is the detailed content of How to Calculate the Distance and Bearing Between Two GPS Points Using Python's Haversine Formula?. For more information, please follow other related articles on the PHP Chinese website!