I want to get the Distance between two latitude and longitude in meter / km . So i am using the below function . It gives me the different result than the google Map.
Can you help me to solve my problem ? i dont understand What is the Problem ?
Code
float[] results = {0};
android.location.Location.distanceBetween(lat1, lon1, lat2, lon2, results);
Current Latitude = 23.012281666666663
Current Longitude = 72.51798333333333
Destination Latitude = 23.1120487
Destination Latitude = 72.5766759
It gives this Result = 12579.679 in Meter, while in google map it gives this result = 17.9 Km
I do not understand why this two gives the different result.
This diagram explains why you get 12.5 and 17.6 kms
To calculate the driving distance (17.6 km) , you need to use the directions API
You can use this 2 function to find the distance
*NOTE:*If you cant get the distance correctly then try setting the MILLION var to 1 cause in my case i have multiplied the lat-long values with 1E6 so have to divide with it.
public double calcdist() {
int MILLION = 1000000;
int EARTH_RADIUS_KM = 6371;
double lat1 = la1 / MILLION;
double lon1 = lo1 / MILLION;
double lat2 = la2 / MILLION;
double lon2 = lo2 / MILLION;
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
double dist = Math
.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad)
* Math.cos(lat2Rad) * Math.cos(deltaLonRad))
* EARTH_RADIUS_KM;
return dist;
}
and
private float round(float dist, int i) {
float p1 = (float) Math.pow(10, i);
dist = dist * p1;
float tmp = Math.round(dist);
return (float) tmp / p1;
}
then use them as
float tempdist = (float) calcdist();
dist = round(tempdist, 2);
Hey I found one source code here and People arround says it will return the correct distance travelling by road. I haven't try this but you may try and tell me if it really works.
GPSSample.java
I dont know how you are passing the Lat - Long Values..Please Try this whole sample code once.
and the code written in android.location.Location.java for this is as below..if you wish can directly use this in your app.
private static void computeDistanceAndBearing(double lat1,
double lon1, double lat2, double lon2, float[] results) {
// Based on http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
// using the "Inverse Formula" (section 4)
int MAXITERS = 20;
// Convert lat/long to radians
lat1 *= Math.PI / 180.0;
lat2 *= Math.PI / 180.0;
lon1 *= Math.PI / 180.0;
lon2 *= Math.PI / 180.0;
double a = 6378137.0; // WGS84 major axis
double b = 6356752.3142; // WGS84 semi-major axis
double f = (a - b) / a;
double aSqMinusBSqOverBSq = (a * a - b * b) / (b * b);
double L = lon2 - lon1;
double A = 0.0;
double U1 = Math.atan((1.0 - f) * Math.tan(lat1));
double U2 = Math.atan((1.0 - f) * Math.tan(lat2));
double cosU1 = Math.cos(U1);
double cosU2 = Math.cos(U2);
double sinU1 = Math.sin(U1);
double sinU2 = Math.sin(U2);
double cosU1cosU2 = cosU1 * cosU2;
double sinU1sinU2 = sinU1 * sinU2;
double sigma = 0.0;
double deltaSigma = 0.0;
double cosSqAlpha = 0.0;
double cos2SM = 0.0;
double cosSigma = 0.0;
double sinSigma = 0.0;
double cosLambda = 0.0;
double sinLambda = 0.0;
double lambda = L; // initial guess
for (int iter = 0; iter < MAXITERS; iter++) {
double lambdaOrig = lambda;
cosLambda = Math.cos(lambda);
sinLambda = Math.sin(lambda);
double t1 = cosU2 * sinLambda;
double t2 = cosU1 * sinU2 - sinU1 * cosU2 * cosLambda;
double sinSqSigma = t1 * t1 + t2 * t2; // (14)
sinSigma = Math.sqrt(sinSqSigma);
cosSigma = sinU1sinU2 + cosU1cosU2 * cosLambda; // (15)
sigma = Math.atan2(sinSigma, cosSigma); // (16)
double sinAlpha = (sinSigma == 0) ? 0.0 : cosU1cosU2
* sinLambda / sinSigma; // (17)
cosSqAlpha = 1.0 - sinAlpha * sinAlpha;
cos2SM = (cosSqAlpha == 0) ? 0.0 : cosSigma - 2.0
* sinU1sinU2 / cosSqAlpha; // (18)
double uSquared = cosSqAlpha * aSqMinusBSqOverBSq; // defn
A = 1
+ (uSquared / 16384.0)
* // (3)
(4096.0 + uSquared
* (-768 + uSquared
* (320.0 - 175.0 * uSquared)));
double B = (uSquared / 1024.0) * // (4)
(256.0 + uSquared
* (-128.0 + uSquared
* (74.0 - 47.0 * uSquared)));
double C = (f / 16.0) * cosSqAlpha
* (4.0 + f * (4.0 - 3.0 * cosSqAlpha)); // (10)
double cos2SMSq = cos2SM * cos2SM;
deltaSigma = B
* sinSigma
* // (6)
(cos2SM + (B / 4.0)
* (cosSigma * (-1.0 + 2.0 * cos2SMSq) - (B / 6.0)
* cos2SM
* (-3.0 + 4.0 * sinSigma * sinSigma)
* (-3.0 + 4.0 * cos2SMSq)));
lambda = L
+ (1.0 - C)
* f
* sinAlpha
* (sigma + C
* sinSigma
* (cos2SM + C * cosSigma
* (-1.0 + 2.0 * cos2SM * cos2SM))); // (11)
double delta = (lambda - lambdaOrig) / lambda;
if (Math.abs(delta) < 1.0e-12) {
break;
}
}
float distance = (float) (b * A * (sigma - deltaSigma));
results[0] = distance;
if (results.length > 1) {
float initialBearing = (float) Math.atan2(
cosU2 * sinLambda, cosU1 * sinU2 - sinU1 * cosU2
* cosLambda);
initialBearing *= 180.0 / Math.PI;
results[1] = initialBearing;
if (results.length > 2) {
float finalBearing = (float) Math.atan2(cosU1
* sinLambda, -sinU1 * cosU2 + cosU1 * sinU2
* cosLambda);
finalBearing *= 180.0 / Math.PI;
results[2] = finalBearing;
}
}
}
Related
Till now, I have inserted all the sets of latitude and longitude in my database after every 5 sec from the path I have travelled.
Now after reaching the destination I have to calculate the distance from the sets of Latitude, longitude. It's not about calculating the travelling distance between two points but to get the total distance travelled from set of lat,long in my database .
I have thought a way of calculating the total distance by getting the distance between the two points
and add them up at last
Is there any better solution than this? please suggest and help
Already read this SO post but not getting how I will get the total distance by using the Google Maps Distance Matrix API
///////service to insert coordinates into the database.
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
String name = arg1.getAction();
if (name.equalsIgnoreCase("Location_Changed")) {
db.insertlatlong(new Latilongi(arg1.getStringExtra("latitude"),
arg1.getStringExtra("longitude"),currentDateandTime));
} else if (arg1.getAction().matches("android.location.PROVIDERS_CHANGED")) {
Toast.makeText(MapActivity.this, "in android.location.PROVIDERS_CHANGED",
Toast.LENGTH_SHORT).show();
}
}
}
you can use the following method that will give you acurate result
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
int Radius = 6371;// radius of earth in Km
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + " KM " + kmInDec
+ " Meter " + meterInDec);
return Radius * c;
}
try this one
private double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
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);
dist = dist * 60 * 1.1515;
if (unit == "K") {
dist = dist * 1.609344;
} else if (unit == "N") {
dist = dist * 0.8684;
}
return (dist);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts decimal degrees to radians :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
You can insert only distance between two co-ordinates and lastly sum up all distances you had in database. Distance achieve like below.
float distanceInMeters = lastLocation.distanceTo(myLocation);
where "lastLocation" and "myLocation" are of Location object.
If you dont have Location object than you can try this.
Location lastLocation = new Location("");
lastLocation.setLatitude(latitude);
lastLocation.setLongitude(longitude);
Location myLocation = new Location("");
myLocation.setLatitude(otherlatitude);
myLocation.setLongitude(otherlongitude);
float distanceInMeters = lastLocation.distanceTo(myLocation);
In My app,i am using map and want to get the distance between from one place to another place by the help of Location. and i am getting location of every point when change the location.
give source and destination lat long and calculate distance in km.
public static double getDistance(double lat1, double lon1, double lat2, double lon2) {
int R = 6371; // Radius of the earth in km
double dLat = deg2rad(lat2 - lat1); // deg2rad below
double dLon = deg2rad(lon2 - lon1);
double a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = R * c; // Distance in km
return d;
}
public static double deg2rad(double deg) {
return deg * (Math.PI / 180);
}
I'm not really good with mathematics but I need to calculate the distance of two different locations of the markers. Something like this:
public double CalculationByDistance(double initialLat, double initialLong, double finalLat, double finalLong){
return distance;
}
Or is there any alternative ways that I can calculate the distance of two markers, also I tried to google for answers.. but couldn't find any.
Reference:
http://en.wikipedia.org/wiki/Haversine_formula
Comments are appreciated :) Thanks!!
Try this, much simpler than Haversine!
Location me = new Location("");
Location dest = new Location("");
me.setLatitude(myLat);
me.setLongitude(myLong);
dest.setLatitude(destLat);
dest.setLongitude(destLong);
float dist = me.distanceTo(dest);
If you want to stick with Haversine, something like this:
public double CalculationByDistance(double initialLat, double initialLong,
double finalLat, double finalLong){
int R = 6371; // km (Earth radius)
double dLat = toRadians(finalLat-initialLat);
double dLon = toRadians(finalLong-initialLong);
initialLat = toRadians(initialLat);
finalLat = toRadians(finalLat);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(initialLat) * Math.cos(finalLat);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
public double toRadians(double deg) {
return deg * (Math.PI/180);
}
Also, you need to create a method toRadians() that convert values from degrees to radians, which is quite easy.
Hope it helps!
From your wikipedia link, applying the formula directly you can do the following:
public double CalculationByDistance(double initialLat, double initialLong, double finalLat, double finalLong){
/*PRE: All the input values are in radians!*/
double latDiff = finalLat - initialLat;
double longDiff = finalLong - initialLong;
double earthRadius = 6371; //In Km if you want the distance in km
double distance = 2*earthRadius*Math.asin(Math.sqrt(Math.pow(Math.sin(latDiff/2.0),2)+Math.cos(initialLat)*Math.cos(finalLat)*Math.pow(Math.sin(longDiff/2),2)));
return distance;
}
Use the below method for calculating the distance of two different locations.
public double getKilometers(double lat1, double long1, double lat2, double long2) {
double PI_RAD = Math.PI / 180.0;
double phi1 = lat1 * PI_RAD;
double phi2 = lat2 * PI_RAD;
double lam1 = long1 * PI_RAD;
double lam2 = long2 * PI_RAD;
return 6371.01 * acos(sin(phi1) * sin(phi2) + cos(phi1) * cos(phi2) * cos(lam2 - lam1));
}
try this
/**
* This is the implementation Haversine Distance Algorithm between two places
* #author ananth
* R = earth’s radius (mean radius = 6,371km)
Δlat = lat2− lat1
Δlong = long2− long1
a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
c = 2.atan2(√a, √(1−a))
d = R.c
*
*/
public class HaversineDistance {
/**
* #param args
* arg 1- latitude 1
* arg 2 — latitude 2
* arg 3 — longitude 1
* arg 4 — longitude 2
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final int R = 6371; // Radious of the earth
Double lat1 = Double.parseDouble(args[0]);
Double lon1 = Double.parseDouble(args[1]);
Double lat2 = Double.parseDouble(args[2]);
Double lon2 = Double.parseDouble(args[3]);
Double latDistance = toRad(lat2-lat1);
Double lonDistance = toRad(lon2-lon1);
Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
Double distance = R * c;
System.out.println(“The distance between two lat and long is::” + distance);
}
private static Double toRad(Double value) {
return value * Math.PI / 180;
}
}
I'm trying to develop my own augmented reality engine.
Searching on internet, I've found this useful tutorial. Reading it I see that the important thing is bearing between user location, point location and north.
The following picture is from that tutorial.
Following it, I wrote an Objective-C method to obtain beta:
+ (float) calculateBetaFrom:(CLLocationCoordinate2D)user to:(CLLocationCoordinate2D)destination
{
double beta = 0;
double a, b = 0;
a = destination.latitude - user.latitude;
b = destination.longitude - user.longitude;
beta = atan2(a, b) * 180.0 / M_PI;
if (beta < 0.0)
beta += 360.0;
else if (beta > 360.0)
beta -= 360;
return beta;
}
But, when I try it, it doesn't work very well.
So, I checked iPhone AR Toolkit, to see how it works (I've been working with this toolkit, but it is so big for me).
And, in ARGeoCoordinate.m there is another implementation of how to obtain beta:
- (float)angleFromCoordinate:(CLLocationCoordinate2D)first toCoordinate:(CLLocationCoordinate2D)second {
float longitudinalDifference = second.longitude - first.longitude;
float latitudinalDifference = second.latitude - first.latitude;
float possibleAzimuth = (M_PI * .5f) - atan(latitudinalDifference / longitudinalDifference);
if (longitudinalDifference > 0)
return possibleAzimuth;
else if (longitudinalDifference < 0)
return possibleAzimuth + M_PI;
else if (latitudinalDifference < 0)
return M_PI;
return 0.0f;
}
It uses this formula:
float possibleAzimuth = (M_PI * .5f) - atan(latitudinalDifference / longitudinalDifference);
Why is (M_PI * .5f) in this formula? I don't understand it.
And continue searching, I've found another page talking about how to calculate distance and bearing of 2 locations. In this page there is another implementation:
/**
* Returns the (initial) bearing from this point to the supplied point, in degrees
* see http://williams.best.vwh.net/avform.htm#Crs
*
* #param {LatLon} point: Latitude/longitude of destination point
* #returns {Number} Initial bearing in degrees from North
*/
LatLon.prototype.bearingTo = function(point) {
var lat1 = this._lat.toRad(), lat2 = point._lat.toRad();
var dLon = (point._lon-this._lon).toRad();
var y = Math.sin(dLon) * Math.cos(lat2);
var x = Math.cos(lat1)*Math.sin(lat2) -
Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
var brng = Math.atan2(y, x);
return (brng.toDeg()+360) % 360;
}
Which one is the right one?
Calculate bearing
//Source
JSONObject source = step.getJSONObject("start_location");
double lat1 = Double.parseDouble(source.getString("lat"));
double lng1 = Double.parseDouble(source.getString("lng"));
// destination
JSONObject destination = step.getJSONObject("end_location");
double lat2 = Double.parseDouble(destination.getString("lat"));
double lng2 = Double.parseDouble(destination.getString("lng"));
double dLon = (lng2-lng1);
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
double brng = Math.toDegrees((Math.atan2(y, x)));
brng = (360 - ((brng + 360) % 360));
Convert Degrees into Radians
Radians = Degrees * PI / 180
Convert Radians into Degrees
Degrees = Radians * 180 / PI
I know this question is old, but here is an easier solution:
float bearing = loc1.bearingTo(loc2);
Try this for accurate result:
private static double degreeToRadians(double latLong) {
return (Math.PI * latLong / 180.0);
}
private static double radiansToDegree(double latLong) {
return (latLong * 180.0 / Math.PI);
}
public static double getBearing() {
//Source
JSONObject source = step.getJSONObject("start_location");
double lat1 = Double.parseDouble(source.getString("lat"));
double lng1 = Double.parseDouble(source.getString("lng"));
// destination
JSONObject destination = step.getJSONObject("end_location");
double lat2 = Double.parseDouble(destination.getString("lat"));
double lng2 = Double.parseDouble(destination.getString("lng"));
double fLat = degreeToRadians(lat1);
double fLong = degreeToRadians(lng1);
double tLat = degreeToRadians(lat2);
double tLong = degreeToRadians(lng2);
double dLon = (tLong - fLong);
double degree = radiansToDegree(Math.atan2(sin(dLon) * cos(tLat),
cos(fLat) * sin(tLat) - sin(fLat) * cos(tLat) * cos(dLon)));
if (degree >= 0) {
return degree;
} else {
return 360 + degree;
}
}
You can test bearing result on http://www.sunearthtools.com/tools/distance.php .
In the formula
float possibleAzimuth = (M_PI * .5f) - atan(latitudinalDifference / longitudinalDifference);
the term (M_PI * .5f) means π/2 which is 90°. That means that it is the same formula that you stated at first, because regarding to the figure above it holds
β = arctan (a/b) = 90° - arctan(b/a).
So both formulas are similar if a refers to the difference in longitude and b in the difference in latitude. The last formula calculates again the same using the first part of my equation.
a in the diagram is the longitude difference, b is the latitude difference therefore in the method you have written you've got them the wrong way round.
a = destination.latitude - user.latitude; // should be b
b = destination.longitude - user.longitude; // should be a
Try switching them and see what happens.
See Palund's response for answers to the rest of your questions.
/*
Kirit vaghela answer has been modified..
Math.sin gives the radian value so to get degree value we need to pass Math.toRadians(value) inside Math.sin() or Math.cos()
*/
double lat1 = 39.099912;
double lat2 = 38.627089;
double lng1 = -94.581213;
double lng2 = -90.200203;
double dLon = (lng2-lng1);
double x = Math.sin(Math.toRadians(dLon)) * Math.cos(Math.toRadians(lat2));
double y = Math.cos(Math.toRadians(lat1))*Math.sin(Math.toRadians(lat2)) - Math.sin(Math.toRadians(lat1))*Math.cos(Math.toRadians(lat2))*Math.cos(Math.toRadians(dLon));
double bearing = Math.toDegrees((Math.atan2(x, y)));
System.out.println("BearingAngle : "+bearing);
If you want you can take a look at the code used in mixare augmented reality engine, it's on github and there's an iPhone version as well: github.com/mixare
inputs are in degrees.
#define PI 3.14159265358979323846
#define RADIO_TERRESTRE 6372797.56085
#define GRADOS_RADIANES PI / 180
#define RADIANES_GRADOS 180 / PI
double calculateBearing(double lon1, double lat1, double lon2, double lat2)
{
double longitude1 = lon1;
double longitude2 = lon2;
double latitude1 = lat1 * GRADOS_RADIANES;
double latitude2 = lat2 * GRADOS_RADIANES;
double longDiff= (longitude2-longitude1) * GRADOS_RADIANES;
double y= sin(longDiff) * cos(latitude2);
double x= cos(latitude1) * sin(latitude2) - sin(latitude1) * cos(latitude2) * cos(longDiff);
// std::cout <<__FILE__ << "." << __FUNCTION__ << " line:" << __LINE__ << " "
return fmod(((RADIANES_GRADOS *(atan2(y, x)))+360),360);
}
I researched a little in this topic, but there are many opinions that don't exactly give a clear image. My problem is this: I'm developing a GPS-based app for Android, in which I want to know distance between my current location specified by Androids LocationManager, and other location in real time. I tried Haversine formula, a Law of Cosines formula, then I discovered, that Android SDK gives me a simple function Location.distanceTo(Location) - I'm not sure what method does this function runs on.
So, the point is, which one will be good for me to use, in situations when real distance between these locations most of the time won't be larger than aprox. 100-200m? Maybe I should check Vincenty's formulae? Is it really that slow? Can someone please explain me what should I choose?
Don't use distanceTo. Use the distanceBetween method as it sounds like you already have the coordinates and that's all you need with this method: Location.distanceBetween() Javadoc
Looking into the Android source for distanceTo(Location), you can see that the result is based on the "Inverse Formula" of geodesy:
Which is based on using the "Inverse Formula" (section 4)
Furthermore, the two methods distanceTo and distanceBetween use the same underlying method. They just have alternative forms of input/output.
For completeness, the full source of this computation is included below, but I encourage you to check out the Location class in android.location for yourself. (P.S. I did not check the correctness of the Android computation. This would be a good exercise!)
private static void computeDistanceAndBearing(double lat1, double lon1,
double lat2, double lon2, float[] results) {
// Based on http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
// using the "Inverse Formula" (section 4)
int MAXITERS = 20;
// Convert lat/long to radians
lat1 *= Math.PI / 180.0;
lat2 *= Math.PI / 180.0;
lon1 *= Math.PI / 180.0;
lon2 *= Math.PI / 180.0;
double a = 6378137.0; // WGS84 major axis
double b = 6356752.3142; // WGS84 semi-major axis
double f = (a - b) / a;
double aSqMinusBSqOverBSq = (a * a - b * b) / (b * b);
double L = lon2 - lon1;
double A = 0.0;
double U1 = Math.atan((1.0 - f) * Math.tan(lat1));
double U2 = Math.atan((1.0 - f) * Math.tan(lat2));
double cosU1 = Math.cos(U1);
double cosU2 = Math.cos(U2);
double sinU1 = Math.sin(U1);
double sinU2 = Math.sin(U2);
double cosU1cosU2 = cosU1 * cosU2;
double sinU1sinU2 = sinU1 * sinU2;
double sigma = 0.0;
double deltaSigma = 0.0;
double cosSqAlpha = 0.0;
double cos2SM = 0.0;
double cosSigma = 0.0;
double sinSigma = 0.0;
double cosLambda = 0.0;
double sinLambda = 0.0;
double lambda = L; // initial guess
for (int iter = 0; iter < MAXITERS; iter++) {
double lambdaOrig = lambda;
cosLambda = Math.cos(lambda);
sinLambda = Math.sin(lambda);
double t1 = cosU2 * sinLambda;
double t2 = cosU1 * sinU2 - sinU1 * cosU2 * cosLambda;
double sinSqSigma = t1 * t1 + t2 * t2; // (14)
sinSigma = Math.sqrt(sinSqSigma);
cosSigma = sinU1sinU2 + cosU1cosU2 * cosLambda; // (15)
sigma = Math.atan2(sinSigma, cosSigma); // (16)
double sinAlpha = (sinSigma == 0) ? 0.0 :
cosU1cosU2 * sinLambda / sinSigma; // (17)
cosSqAlpha = 1.0 - sinAlpha * sinAlpha;
cos2SM = (cosSqAlpha == 0) ? 0.0 :
cosSigma - 2.0 * sinU1sinU2 / cosSqAlpha; // (18)
double uSquared = cosSqAlpha * aSqMinusBSqOverBSq; // defn
A = 1 + (uSquared / 16384.0) * // (3)
(4096.0 + uSquared *
(-768 + uSquared * (320.0 - 175.0 * uSquared)));
double B = (uSquared / 1024.0) * // (4)
(256.0 + uSquared *
(-128.0 + uSquared * (74.0 - 47.0 * uSquared)));
double C = (f / 16.0) *
cosSqAlpha *
(4.0 + f * (4.0 - 3.0 * cosSqAlpha)); // (10)
double cos2SMSq = cos2SM * cos2SM;
deltaSigma = B * sinSigma * // (6)
(cos2SM + (B / 4.0) *
(cosSigma * (-1.0 + 2.0 * cos2SMSq) -
(B / 6.0) * cos2SM *
(-3.0 + 4.0 * sinSigma * sinSigma) *
(-3.0 + 4.0 * cos2SMSq)));
lambda = L +
(1.0 - C) * f * sinAlpha *
(sigma + C * sinSigma *
(cos2SM + C * cosSigma *
(-1.0 + 2.0 * cos2SM * cos2SM))); // (11)
double delta = (lambda - lambdaOrig) / lambda;
if (Math.abs(delta) < 1.0e-12) {
break;
}
}
float distance = (float) (b * A * (sigma - deltaSigma));
results[0] = distance;
if (results.length > 1) {
float initialBearing = (float) Math.atan2(cosU2 * sinLambda,
cosU1 * sinU2 - sinU1 * cosU2 * cosLambda);
initialBearing *= 180.0 / Math.PI;
results[1] = initialBearing;
if (results.length > 2) {
float finalBearing = (float) Math.atan2(cosU1 * sinLambda,
-sinU1 * cosU2 + cosU1 * sinU2 * cosLambda);
finalBearing *= 180.0 / Math.PI;
results[2] = finalBearing;
}
}
}