Actually I want to get exact distance between two lat and lang. But I have tried three different functions but all are not giving me right distance.
Here is Code:
private double distance(double lat1, double lon1, double lat2, double lon2) {
//first formula
Location startPoint=new Location("locationA");
startPoint.setLatitude(lat1);
startPoint.setLongitude(lon1);
Location endPoint=new Location("locationA");
endPoint.setLatitude(lat2);
endPoint.setLongitude(lon2);
double distancee=startPoint.distanceTo(endPoint);
// second formula
float[] results=new float[1];
Location.distanceBetween( lat1, lon1, lat2, lon2, results);
float result= 0;
if (results != null) {
result = results[0];
}
double dvar=(double)result;
//third formula
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;
return (distancee);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
These all are not giving me right distance please guide me how can I perform this goal
The distance that you are getting is a straight line between the two points, and as you found out by using the tool in GoogleMaps
it is correct. In order to get the distance which takes into account the roads and everything else, you will have to use Google Directions Api. You will need to make an HTTP Request using Retrofit
or OkHttp
or something else.
In your request, you will need to provide origin and destination and as a response, you will get a bunch of information, including the distance, you can find more info on the docs website that I linked.