Home >Backend Development >Python Tutorial >Why is My Latitude/Longitude Distance Calculation Incorrect?
Calculating Distance Using Latitude and Longitude: Addressing a Coding Error
While attempting to implement the formula for finding distances based on latitude and longitude, a user encountered an unexpected result. The formula, as given in the referenced applet, worked correctly for the test points provided. However, the user's code returned an inaccurate distance value.
Code Inspection
Upon examining the code, it was discovered that the user was using the deprecated Vincenty distance calculation method, which has been replaced by the more accurate geopy.distance.distance() function in GeoPy version 1.13. The haversine formula, which the user's code was utilizing, assumes a spherical earth model and can introduce errors of up to 0.5%.
Using geopy.distance
To resolve the issue, it is recommended to switch to using the more accurate geopy.distance.geodesic() function for calculating the distance. This function utilizes ellipsoidal models, such as WGS-84, and provides a more precise result:
<code class="python">import geopy.distance coords_1 = (52.2296756, 21.0122287) coords_2 = (52.406374, 16.9251681) distance = geopy.distance.geodesic(coords_1, coords_2).km print(distance)</code>
With the revised code, the distance between the two points is calculated accurately as 279.352 kilometers.
The above is the detailed content of Why is My Latitude/Longitude Distance Calculation Incorrect?. For more information, please follow other related articles on the PHP Chinese website!