Calculating Distance between Two Points Using Latitude and Longitude
Determining the distance between two points on a map is a common task in various fields, from navigation to GIS. One method for calculating this distance accurately is to use the Haversine formula, which is designed specifically for working with latitude and longitude coordinates.
Haversine Formula Implementation in Java
A precise implementation of the Haversine formula in Java is presented below:
<code class="java">public static double distance(double lat1, double lon1, double lat2, double lon2) { final int R = 6371; // Radius of the earth in kilometers 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 return distance; }</code>
Usage of the Formula
To calculate the distance between two points with coordinates (lat1, lon1) and (lat2, lon2), simply pass these values as parameters to the distance method. The result is returned in meters.
Example:
<code class="java">double lat1 = 41.881832; double lon1 = -87.623177; double lat2 = 41.889809; double lon2 = -87.621882; double distance = distance(lat1, lon1, lat2, lon2); System.out.println("Distance between the points: " + distance + " meters");</code>
Considerations for Accuracy
The precision of the result depends on the accuracy of the input coordinates. It's crucial to ensure that the latitude and longitude values are provided in the correct format and with appropriate units (e.g., decimal degrees).
The above is the detailed content of How to Calculate the Distance Between Two Points Using Latitude and Longitude?. For more information, please follow other related articles on the PHP Chinese website!