I have two locations and I want to calculate distance in meter. I wrote some code but it's not working perfectly.
private void getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2)
{
Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);
Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);
int R = 6371; // km
double dLat = deg2rad(lat2-lat1);
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 distanceInMeters = R * c;
Log.e("distanceInMeters",distanceInMeters/10000+"mm");
}
public double deg2rad(double deg) {
return deg * (Math.PI/180);
}
How can I calculate distance in meter? My goal is, if meter > 200 do something. How can i solve my problem?
There is no need to re-invent the wheel for this.
You can just use the Location.distanceBetween()
method.
From the documentation:
Computes the approximate distance in meters between two locations
Here is a simple example:
private float getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2) {
float[] distance = new float[2];
Location.distanceBetween( lat1, lon1,
lat2, lon2, distance);
return distance[0];
}
If the result array has more than just index zero populated, the other indices each contain a bearing (initial and final).
A bearing is a number that specifies a compass direction.
From http://www.geomidpoint.com/destination/help.html :
The bearing (or azimuth) is the compass direction to travel from the starting point, and must be within the range 0 to 360. 0 represents north, 90 is east, 180 is south and 270 is west.