Home >Java >javaTutorial >How to Calculate the Distance Between Two Points on Earth Using Latitude and Longitude?
Latitude and Longitude: Calculating Distance Between Two Points
Calculating the distance between two points on the globe requires knowledge of their latitudes and longitudes. While many solutions exist, one accurate method for determining the distance between two coordinates is the Haversine formula.
A Java implementation of the Haversine method, provided by Dommer, is:
<code class="java">final double RADIUS = 6371.01; double temp = Math.cos(Math.toRadians(latA)) * Math.cos(Math.toRadians(latB)) * Math.cos(Math.toRadians((latB) - (latA))) + Math.sin(Math.toRadians(latA)) * Math.sin(Math.toRadians(latB)); return temp * RADIUS * Math.PI / 180;</code>
However, small errors can accumulate when using this method for large data sets like GPS tracks.
An improved implementation that also considers height differences between points is:
<code class="java">public static double distance(double lat1, double lat2, double lon1, double lon2, double el1, double el2) { final int R = 6371; // Radius of the earth double latDistance = Math.toRadians(lat2 - lat1); double lonDistance = Math.toRadians(lon2 - lon1); double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double distance = R * c * 1000; // convert to meters double height = el1 - el2; distance = Math.pow(distance, 2) + Math.pow(height, 2); return Math.sqrt(distance); }</code>
The above is the detailed content of How to Calculate the Distance Between Two Points on Earth Using Latitude and Longitude?. For more information, please follow other related articles on the PHP Chinese website!