1/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
2/*:: :*/
3/*:: This routine calculates the distance between two points (given the :*/
4/*:: latitude/longitude of those points). It is being used to calculate :*/
5/*:: the distance between two locations using GeoDataSource (TM) products :*/
6/*:: :*/
7/*:: Definitions: :*/
8/*:: Southern latitudes are negative, eastern longitudes are positive :*/
9/*:: :*/
10/*:: Function parameters: :*/
11/*:: lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees) :*/
12/*:: lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees) :*/
13/*:: unit = the unit you desire for results :*/
14/*:: where: 'M' is statute miles (default) :*/
15/*:: 'K' is kilometers :*/
16/*:: 'N' is nautical miles :*/
17/*:: Worldwide cities and other features databases with latitude longitude :*/
18/*:: are available at https://www.geodatasource.com :*/
19/*:: :*/
20/*:: For enquiries, please contact sales@geodatasource.com :*/
21/*:: :*/
22/*:: Official Web site: https://www.geodatasource.com :*/
23/*:: :*/
24/*:: GeoDataSource.com (C) All Rights Reserved 2019 :*/
25/*:: :*/
26/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
27
28import java.util.*;
29import java.lang.*;
30import java.io.*;
31
32class DistanceCalculator
33{
34 public static void main (String[] args) throws java.lang.Exception
35 {
36 System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "M") + " Miles\n");
37 System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "K") + " Kilometers\n");
38 System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "N") + " Nautical Miles\n");
39 }
40
41 private static double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
42 if ((lat1 == lat2) && (lon1 == lon2)) {
43 return 0;
44 }
45 else {
46 double theta = lon1 - lon2;
47 double dist = Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2)) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta));
48 dist = Math.acos(dist);
49 dist = Math.toDegrees(dist);
50 dist = dist * 60 * 1.1515;
51 if (unit.equals("K")) {
52 dist = dist * 1.609344;
53 } else if (unit.equals("N")) {
54 dist = dist * 0.8684;
55 }
56 return (dist);
57 }
58 }
59}