Calculate distance between two locations in Java

Words
212
Reading
1 min
Listen
Play
9y

For the spatial applications there is always need to calculate the distance between two geographic points. In Java it is possible to make this calculation very easly with LatLong java library.

The calculation is based on the Haversine distance that you can find best explained here https://en.wikipedia.org/wiki/Haversine_formula

The code in the snippet bellow explains this in just a few lines where each step is well commented


public class Main2DistanceCalculator

public static void main (String [] args) throws Exception{

// define the lat long for the first geograaphic point
double lat1 = 45.068893;
double lat2 = 45.03078400;

// define the second point
double lon1 = 7.694667;
double lon2 =   7.65651400;

// create two locations with the object LatLonPoint
LatLonPoint gp1 = new LatLonPoint(lat1, lon1);
LatLonPoint gp2 = new LatLonPoint(lat2, lon2);

// calculate the distance between the points with the method getHarversineDistance();
double d = LatLonUtils.getHaversineDistance(gp1, gp2);  
System.out.println( d);

       }
} 

The will give as result or the distance in meters between the two geographic points

In the future datatreemap will publish a guide on how to visualize geographic points in Google Earth and visualize the distance between them. Just like in the following graphics.

Schermata 2017-10-29 alle 07.36.03.png

If you enjoyed this article guide on distance calculation between two points please share and stay tuned for more ;-)

Calculate distance between two locations in Java | Ecency