Calculate distance between two locations in Java

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 Harversine distance that you can find best explained here

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

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);

           }
	} 	

Important note: the code has to import the LatLonLib.java which is not anymore available online so download the entire project from here :

By running this code you can see the result or the distance in meters between the two points

If you enjoyed this article guide on distance calculation between two points please share

Tweet

or follow data map on twitter..

Follow @datatreemap2t