Calculating Distance between Two Points Using Latitude and Longitude
To accurately calculate the distance between two points based on their latitude and longitude, it's crucial to consider the curvature of the Earth's surface. The Haversine method, a well-known formula, addresses this curvature and provides precise results.
Dommer's Code
Dommer's code utilizes the Haversine formula to compute the distance. However, it doesn't account for any height differences between the two points.
Recommended Implementation
For GPS tracks or applications where altitude is a factor, consider this modified implementation:
<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>
This code incorporates both the Haversine formula and height differences to calculate the distance between two points accurately.
The above is the detailed content of How to Calculate Distance Between Two Points Using Latitude, Longitude, and Altitude?. For more information, please follow other related articles on the PHP Chinese website!