Created
October 11, 2014 19:51
-
-
Save sahutd/61aa9db80cedebe4ffa1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class distanceCalculator | |
{ | |
public static final double R = 6372.8; | |
public static Information getInformation(double lat1, double long1, | |
double lat2, double long2) | |
{ | |
double distance = haversine(lat1, long1, lat2, long2); | |
String bearing = headingToString2(bearing(lat1, long1, lat2, long2)); | |
return new Information(distance, bearing); | |
} | |
public static double haversine(double lat1, double lon1, double lat2, double lon2) | |
{ | |
double dLat = Math.toRadians(lat2 - lat1); | |
double dLon = Math.toRadians(lon2 - lon1); | |
lat1 = Math.toRadians(lat1); | |
lat2 = Math.toRadians(lat2); | |
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2); | |
double c = 2 * Math.asin(Math.sqrt(a)); | |
return R * c; | |
} | |
protected static double bearing(double lat1, double lon1, double lat2, double lon2) | |
{ | |
double longitude1 = lon1; | |
double longitude2 = lon2; | |
double latitude1 = Math.toRadians(lat1); | |
double latitude2 = Math.toRadians(lat2); | |
double longDiff= Math.toRadians(longitude2-longitude1); | |
double y= Math.sin(longDiff)*Math.cos(latitude2); | |
double x=Math.cos(latitude1)*Math.sin(latitude2)-Math.sin(latitude1)*Math.cos(latitude2)*Math.cos(longDiff); | |
return (Math.toDegrees(Math.atan2(y, x))+360)%360; | |
} | |
public static String headingToString2(double x) | |
{ | |
String directions[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW", "N"}; | |
return directions[ (int)Math.round(((x % 360) / 45)) ]; | |
} | |
public static void main(String[] args) | |
{ | |
System.out.println(getInformation(12.58, 77.34, 28.31, 77.2)); | |
System.out.println(haversine(12.58, 77.34, 28.31, 77.2)); | |
} | |
} | |
class Information | |
{ | |
String bearing; | |
double distance; | |
public Information(double distance, String bearing) | |
{ | |
this.bearing = bearing; | |
this.distance = distance; | |
} | |
public String toString() | |
{ | |
return "" + this.bearing + " " + this.distance + "kms"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment