Home > Java > javaTutorial > body text

How to Calculate the Distance Between Two Points Using Latitude and Longitude?

Linda Hamilton
Release: 2024-10-31 13:09:04
Original
1004 people have browsed it

How to Calculate the Distance Between Two Points Using Latitude and Longitude?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!