Java calculates the distance between two GPs coordinate points
1. LAT1 Lung1 represents the latitude and longitude of a point, Lat2 Lung2 the latitude and longitude of B point;
2. The difference between the latitude of A=lat1–lat2 two points b=lung1-lung2 the difference of longitude of two points;
3.6378.137 is the earth radius, the unit is kilometer;
The calculated result unit is a kilometer.
The code from Google Maps's script is used to calculate the latitude and longitude between two points.
Private Const Double Earth_radius = 6378.137;
private static Double rad (double D)
{
return d * math.pi/180.0;
}
public static double Getdistance (double lat1, double lng1, double lat2, double lng2)
{
Double RADLAT1 = rad (LAT1);
Double radLat2 = rad (LAT2);
Double A = RADLAT1-RADLAT2;
Double b = rad (lng1)-Rad (LNG2);
Math.Cos (RADLAT1) *math.cos (RADLAT2) *math.pow (Math.sin (B/2), 2));
s = S * earth_radius;
s = Math.Round (S * 10000)/10000;
return s;
}
The following code can be used in Android to get the distance
Public double getdistance (double lat1, double lon1, double lat2, double lon2) {
Float[] Results=new float[1];
Location.distancebetween (LAT1, Lon1, LAT2, Lon2, results);
return results[0];
}
In other devices if there is no Android-like location of the Distancebetween method to use the following code to obtain
The result of this calculation is a mile, and if you want to convert it to a kilometer, multiply by 1.609344 if you need to multiply it by 0.8684.
Double distance (double lat1, double lon1, double lat2, double lon2) {
Double theta = Lon1-lon2;
Double dist = Math.sin (Deg2rad (LAT1)) * Math.sin (Deg2rad (LAT2))
+ Math.Cos (Deg2rad (LAT1)) * Math.Cos (Deg2rad (LAT2))
* Math.Cos (Deg2rad (theta));
Dist = Math.acos (dist);
Dist = rad2deg (dist);
Double miles = Dist * 60 * 1.1515;
return miles;
}
//Convert angle to radians
static double Deg2rad (double degree) {
return degree/180 * MATH.PI;
}