Core Java

Calculate the Distance Between Two Coordinates in Java

Calculating the distance between two coordinates is often an interesting learning. In this article, we will see a practical approach to calculating the distance by using three different mathematical approaches. Let’s explore a practical approach to calculate the distance between two coordinates in Java.

1. Equirectangular Distance Approximation

Equirectangular Distance Approximation is a straightforward method used to calculate the distance between two points on the Earth’s surface based on their latitude and longitude coordinates. Although not as precise as some other methods, it provides a reasonably close estimate and is computationally efficient, making it suitable for various applications where high accuracy is not critical. While this method provides a fast approximation of the distance, it’s important to note that it becomes less accurate for longer distances and at higher latitudes due to the distortion introduced by the equirectangular projection. For more accurate results, especially over long distances, other formulas such as the Haversine Formula or Vincenty’s Formulae are often preferred.

1.1 Code

Here’s an example of how to do this:

EquirectangularDistance.java

public class EquirectangularDistance {
    public static void main(String[] args) {
        double lat1 = Math.toRadians(52.5200);
        double lon1 = Math.toRadians(13.4050);
        double lat2 = Math.toRadians(48.8566);
        double lon2 = Math.toRadians(2.3522);
        
        double distance = calculateEquirectangularDistance(lat1, lon1, lat2, lon2);
        System.out.println("Equirectangular Distance: " + distance + " km");
    }
    
    public static double calculateEquirectangularDistance(double lat1, double lon1, double lat2, double lon2) {
        double x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
        double y = (lat2 - lat1);
        return Math.sqrt(x * x + y * y) * 6371; // Earth radius in kilometers
    }
}

The given Java code calculates the distance between two geographical coordinates using the Equirectangular Distance Approximation method. First, the latitude and longitude values of the two points are converted from degrees to radians, as trigonometric functions in Java work with radians. The calculateEquirectangularDistance method computes the differences in longitude and latitude between the two points. By approximating the Earth’s surface as a flat plane using the equirectangular projection, it calculates the x-coordinate and y-coordinate differences. The distance between the two points on this flat plane is then determined using the Pythagorean theorem. Finally, the calculated distance in kilometers is printed to the console.

The sample output demonstrates the result of this calculation, which may vary based on the specific input coordinates used in the program.

Console output

Equirectangular Distance: 876.2515960636774 km

2. Haversine Formula

The Haversine Formula is a mathematical formula used to calculate the shortest distance between two points on the surface of a sphere, given their latitude and longitude in decimal degrees. It’s commonly employed to compute distances between locations on Earth, making it particularly useful in applications related to navigation, geolocation, and mapping. The formula itself is derived from the law of haversines, which relates the sides and angles of spherical triangles. It’s important to note that the Haversine Formula assumes a perfectly spherical Earth, which introduces minor inaccuracies. For more precise distance calculations, especially over long distances, more complex models like Vincenty’s Formulae, which take into account the Earth’s ellipsoidal shape, are used.

2.1 Code

Here’s an example of how to do this:

HaversineDistance.java

public class HaversineDistance {
    public static void main(String[] args) {
        double lat1 = Math.toRadians(52.5200);
        double lon1 = Math.toRadians(13.4050);
        double lat2 = Math.toRadians(48.8566);
        double lon2 = Math.toRadians(2.3522);
        
        double distance = calculateHaversineDistance(lat1, lon1, lat2, lon2);
        System.out.println("Haversine Distance: " + distance + " km");
    }
    
    public static double calculateHaversineDistance(double lat1, double lon1, double lat2, double lon2) {
        double dlon = lon2 - lon1;
        double dlat = lat2 - lat1;
        double a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon / 2), 2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return 6371 * c; // Earth radius in kilometers
    }
}

The provided Java code calculates the distance between two geographical coordinates using the Haversine Formula, a mathematical method designed to find the shortest distance between two points on the surface of a sphere, such as Earth. The latitude and longitude values of the two points are first converted from degrees to radians, as trigonometric functions in Java operate in radians. The calculateHaversineDistance method then computes the differences in longitude and latitude between the two points. Using the Haversine Formula, the intermediate values are determined, representing the square of half the chord length between the points and the angular separation between the points in radians, respectively. The final distance between the two coordinates on Earth’s surface is computed by multiplying the Earth’s radius (considered as 6371 kilometers) with the calculated. The resulting distance in kilometers is printed on the console.

The sample output demonstrates the distance calculated using this method, although slight variations may occur due to the precision of floating-point arithmetic.

Console output

Haversine Distance: 878.0453150742279 km

3. Vincenty’s Formula

Vincenty’s Formulae are a set of algorithms used to calculate the distance between two points on the surface of an ellipsoid, such as Earth, more accurately than the Haversine Formula. Developed by Thaddeus Vincenty, these formulas take into account the Earth’s ellipsoidal shape, making them suitable for precise geodetic calculations over long distances. Unlike the Haversine Formula, which assumes a perfect sphere, Vincenty’s Formulae consider the flattening of the Earth’s shape due to its rotation.

Vincenty’s Formulae include two main formulas: one for calculating the distance between two points (inverse problem) and another for determining the destination point given a starting point, initial azimuth, and distance (direct problem).

  • For the inverse problem (calculating a distance between two points), Vincenty’s formula involves iterative solutions to compute the geodesic distance accurately. It considers the ellipsoidal shape of the Earth and corrects for the flattening effect. The formula takes latitude, longitude, and ellipsoid parameters into account, providing a highly accurate result for geodesic distances.
  • For the direct problem (finding a destination point), Vincenty’s formula calculates the latitude and longitude of a point at a given distance and azimuth from a starting point. This involves solving a system of equations iteratively to obtain precise coordinates on the ellipsoid.

These formulas provide a significant improvement over simpler methods like the Haversine Formula, especially for long distances and at high latitudes, where the Earth’s ellipsoidal shape has a noticeable impact on calculations.

3.1 Code

Calculating the distance between two coordinates using Vincenty’s Formulae involves complex mathematical calculations. To simplify the implementation, you can use libraries like GeographicLib, which provide accurate and optimized implementations of Vincenty’s Formulae. Here’s an example of how you can calculate the distance between two coordinates using GeographicLib in Java:

First, include the GeographicLib library in your project. If you are using Maven, add the following dependency to your pom.xml:

pom.xml

<dependency>
    <groupId>net.sf.geographiclib</groupId>
    <artifactId>GeographicLib</artifactId>
    <version>1.50</version> <!-- Use the latest version -->
</dependency>

Then, you can use the GeographicLib library to calculate the distance:

VincentyDistance.java

import net.sf.geographiclib.Geodesic;
import net.sf.geographiclib.GeodesicData;

public class VincentyDistance {
    public static void main(String[] args) {
        // Latitude and longitude coordinates of two points in degrees
        double lat1 = 52.5200;
        double lon1 = 13.4050;
        double lat2 = 48.8566;
        double lon2 = 2.3522;
        
        // Calculate the distance using Vincenty's Formulae
        Geodesic geodesic = Geodesic.WGS84;
        GeodesicData result = geodesic.Inverse(lat1, lon1, lat2, lon2);
        double distance = result.s12 / 1000.0; // Distance in kilometers
        
        // Print the calculated distance
        System.out.println("Vincenty's Distance: " + distance + " km");
    }
}

In this example, the GeographicLib library’s Geodesic class is used to perform the calculation. The Inverse method calculates the geodesic distance between the two points in meters (result.s12), which is then converted to kilometers for the output. Make sure to adjust the latitude and longitude values of lat1, lon1, lat2, and lon2 according to the coordinates you want to calculate the distance for.

Here’s the output of the Java code:

Console output

Vincenty's Distance: 1054.0845255943883 km

4. Conclusion

To calculate the distance between two coordinates in Java is a fundamental task in various applications, including mapping, navigation, and geolocation services. Different methods, such as the Equirectangular Distance Approximation, Haversine Formula, and more advanced algorithms like Vincenty’s Formulae, offer varying levels of accuracy and computational complexity.

The Equirectangular Distance Approximation provides a simple and fast way to estimate distances but may lack precision for long distances due to the distortion introduced by the projection. The Haversine Formula, considering the Earth as a sphere, offers better accuracy than the Equirectangular method but still simplifies the Earth’s shape, leading to minor inaccuracies, especially for very long distances.

For highly accurate geodetic calculations, Vincenty’s Formulae are employed. These formulas consider the Earth’s ellipsoidal shape and provide precise results over long distances and at high latitudes. While more computationally intensive, they are crucial in applications where accuracy is paramount.

Choosing the appropriate method depends on the specific use case. Simple applications with limited accuracy requirements might opt for the Equirectangular Distance Approximation or Haversine Formula, while advanced applications, such as geodetic surveys and satellite navigation systems, rely on sophisticated algorithms like Vincenty’s Formulae to ensure precise results. Understanding the strengths and limitations of these methods is essential for selecting the most suitable approach for a given scenario.

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button