Home >Java >javaTutorial >How to Accurately Calculate Distance Between Two Points Using Latitude, Longitude, and Altitude?
Problem:
The provided Java code snippet calculates the distance between two points based on their latitude and longitude. The concern is that the formula used may produce slightly inaccurate results, especially when there are multiple points over a significant distance.
Solution:
To address this issue, here's a Java implementation of the Haversine method that takes into account height differences as well:
<code class="java">/** * Calculate distance between two points in latitude and longitude taking * into account height difference. If you are not interested in height * difference pass 0.0. Uses Haversine method as its base. * * lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters * el2 End altitude in meters * @returns Distance in Meters */ 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>
This implementation accurately calculates the distance while also incorporating height differences. It uses the Haversine method as the foundation while considering the height differential between the two points.
The above is the detailed content of How to Accurately Calculate Distance Between Two Points Using Latitude, Longitude, and Altitude?. For more information, please follow other related articles on the PHP Chinese website!