convert getLastLocation() result into separate latitude and longitude - android

I successfully retrieved the last location. I found many answers on SO about calculating the difference in distance between two points, but they seem to have their latitude and longitude separated?
My result is this(numbers changed for example):
Location[fused 12.345678,-123.456789 acc=30 et=+19h26m17s811ms]
How do I separate the latitude and longitude for use like this:
float[] results = new float[3];
Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
float distanceInMeters = results[0]
I found this code on this stack overflow question: distance between two locations is not right?

A Location has 2 methods to calculate the distance to another Location:
static void distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)which writes the distance to the results array
float distanceTo(Location dest) which returns the distance as a float.
So you can either call distanceTo on your Location-object, or you can call Location.distanceBetween and pass in the 2 Latitude/Longitude pairs.

Related

Android Distance between location, What the result mean

I have a function that return the distance between 2 locations
This is my function
public static float GetDistance(Location locationA, Location locationB ){
float distance = locationA.distanceTo(locationB);
return distance;
}
The float result what does it mean? air distance in kilometers?
I get 1.1 or 1.9 what does this result mean
Thanks
I think that can help you :
Calculating distance between two geographic locations
Returns the approximate distance in meters between this location and the given location. Distance is defined using the WGS84 ellipsoid.

Getting distance between farLat, farLng and nearLat, nearLng

I am getting far and near LatLng as below :
mFarLeft = mMapView.getProjection().getVisibleRegion().farLeft;
mFarRight = mMapView.getProjection().getVisibleRegion().farRight;
mNearLeft = mMapView.getProjection().getVisibleRegion().nearLeft;
mNearRight = mMapView.getProjection().getVisibleRegion().nearRight;
Now, How can I calculate the distance between this far and near points?
Is there any method available to get distance in KM and Feet?
The fields farLeft, farRight, etc. are actually LatLng objects, according to the Android documentation. However, there is a field latLngBounds which represents the smallest bounding box including the visible region. This bounds object itself has two LatLng fields for the northeast and southwest corners of the box. Using the Haversine formula we can compute the distance between the corners of this box. For example, if you wanted to compute the height of the bounding box we can try:
public static double haversine(double lat1, double lon1, double lat2, double lon2) {
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.pow(Math.sin(dLat / 2),2) + Math.pow(Math.sin(dLon / 2),2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.asin(Math.sqrt(a));
return 6372.8 * c; // in kilometers
// if you want to return feet, then use 6372.8 * 3280.84 instead
}
public static void main(String[] args) {
LatLng ne = mMapView.getProjection().getVisibleRegion().latLngBounds.northeast;
LatLng sw = mMapView.getProjection().getVisibleRegion().latLngBounds.southwest;
double latLow = sw.latitude;
double latHigh = ne.latitude;
double longitude = sw.longitude;
// now compute the "height" of the bounding box
// note that the longitude value is the same
double height = haversine(latLow, longitude, latHigh, longitude);
}
Google provides a utility library for Maps that can, among other things,
Calculate distances, areas and headings via spherical geometry
Using the spherical geometry utilities in SphericalUtil, you can compute distances, areas, and headings based on latitudes and longitudes. Here are some of the methods available in the utility:
computeDistanceBetween() – Returns the distance, in meters, between two latitude/longitude coordinates.
computeHeading() – Returns the bearing, in degrees, between two latitude/longitude coordinates.
computeArea() – Returns the area, in square meters, of a closed path on the Earth.
interpolate() – Returns the latitude/longitude coordinates of a point that lies a given fraction of the distance between two given points. You can use this to animate a marker between two points, for example.
Refer to the reference documentation for a full list of methods in the utility.
The library is available on maven central.
dependencies {
compile 'com.google.maps.android:android-maps-utils:0.5+'
}
Source: https://developers.google.com/maps/documentation/android-api/utility/

How to get latitude, longitude maximum and minimum from a center point

I have a Geopoint that is the current position of the user. I know its latitude and longitude. I would like to get a square perimeter 50km around the user position so I need to know what are the min & max latitude and the min&max longitude around that given poin, in java.
May someone helps me out with that ?
Thanks in advance ?
Just found out the solution. If you have a given point P(lat, long).
If you need to get 50 km around square perimeter for example, you need to take in consideration earth radius. Below how to do it:
double R = 6371; // earth radius in km
double radius = 50; // km
double latMin = lon - Math.toDegrees(radius/R/Math.cos(Math.toRadians(lat)));
double latMax = lon + Math.toDegrees(radius/R/Math.cos(Math.toRadians(lat)));
double longMax = lat + Math.toDegrees(radius/R);
double longMin = lat - Math.toDegrees(radius/R);
The real answer is here: credit to the real answerer

Defining a threshold for Distance between two GEO Locations?

I am getting two GEO locations in my application and I have to calculate distance between them and after distance calculation I have to compare that result with the a defined threshold which is in my case 50 meters, how would I define that threshold in float. Also, Currently I my android fone is at the same location, but I always get the calculated distance between my 2 two geolocations determined after an interval to be more than 50 meters. How is it possible? I am taking threshold of 50 meters as:
private static final float DISTANCE_CHANGE_METERS = 50.0f; //50 meters
and I am calculating distance through following formula I found on StackOverflow:
public static float distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
int meterConversion = 1609;
return new Float(dist * meterConversion).floatValue();
}
Kindly help me out in this regard. Thanks!
Currently my android phone is at the same location, but I always get the calculated distance between my 2 two geolocations determined after an interval to be more than 50 meters. How is that possible?
It actually depends on how you are passing the latitude and longitude to the distFrom function. Just to remind you that there is a simpler way to calculate the distance.
You can use just distanceTo() function in android API using Location to calculate the distance between two places like this:
Location locationA = new Location("point A");
locationA.setLatitude(latA); // co-ordinates in double
locationA.setLongitude(lngA);
Location locationB = new Location("point B");
locationB.setLatitude(latB);
locationB.setLongitude(lngB);
float distance = locationA.distanceTo(locationB);
If after using this also you are getting a distance greater than 50 meters then your co-ordinates that you are providing are not that accurate. Its perfectly fine because its tough to get accuracy with less that 50 meter precision. It would be most accurate if you are using internet along with GPS. If you see here, even if you use ACCURACY_HIGH as a criteria to choose a Location Provider, it provides accuracy of less than 100 meters. It can be accurate upto 100, 70 or even 50 meters. So even the most accurate option is not guaranteed to give extreme accuracy. If you are using GPS/Network provider for getting Location, then it your situation is very much possible. Getting location using `Network Provider1 is also not that accurate as it can catch signals of 2 network towers on different occasions, which can be well apart physically.
Hope it helps and clears the point to some extent. Its the problem to accuracy of your Location Provider.
Could you just do:
if (distFrom(lat1,lng1,lat2,lng2) > DISTANCE_CHANGE_METERS)
{
//greater than threshhold
}

Sort list of lon\lat points, start with nearest

I have location from GPS (lon_base, lat_base).
I have a list of locations (lon1, lat1|lon2, lat2|lon3, lat3...)
This list is very long and is around the world.
My questions are:
1. How do I get from that list only the lon\lat that are 1 mile from my lon_base\lat_base?
2. How do I sort them from closest to farthest?
Thanks in advance!
public static List<Location> sortLocations(List<Location> locations, final double myLatitude,final double myLongitude) {
Comparator comp = new Comparator<Location>() {
#Override
public int compare(Location o, Location o2) {
float[] result1 = new float[3];
android.location.Location.distanceBetween(myLatitude, myLongitude, o.Lat, o.Long, result1);
Float distance1 = result1[0];
float[] result2 = new float[3];
android.location.Location.distanceBetween(myLatitude, myLongitude, o2.Lat, o2.Long, result2);
Float distance2 = result2[0];
return distance1.compareTo(distance2);
}
};
Collections.sort(locations, comp);
return locations;
}
Where the List of Locations is a list containing your own Location class, not the android.location.Location.
You may use the great circle distance to calculate the distance between two points whose you know the latitude-longitude coordinates. The formulae are quite easy to code:
static double distance(double fromLat, double fromLon, double toLat, double toLon) {
double radius = 6378137; // approximate Earth radius, *in meters*
double deltaLat = toLat - fromLat;
double deltaLon = toLon - fromLon;
double angle = 2 * Math.asin( Math.sqrt(
Math.pow(Math.sin(deltaLat/2), 2) +
Math.cos(fromLat) * Math.cos(toLat) *
Math.pow(Math.sin(deltaLon/2), 2) ) );
return radius * angle;
}
You want to define your own Comparator that, in general, looks something like this:
LonLat myHouse = /* whatever */ ;
Comparable comp = new Comparable () {
LonLat a;
int compareTo (Object b) {
int aDist = calcDistance(a, myHouse) ;
int bDist = calcDistance(b, myHouse) ;
return aDist - bDist;
}
};
myLonLatList.sort(lonLatList, comp);
where calcDistance() simply calculates the distance between the two points. If you're on Android, I think Google Maps has a function somewhere in their API that will do this for you.
EDIT : You'll want your calcDistance() function to look like ChrisJ's distance function.
-tjw
You can use followig approximation (since 1 mile is much smaller than the radius of the earth) to calculate the distances from your base:
dx = cos(phi_base) * (theta - theta_base)
dy = phi - phi_base
dist = sqrt(dx*dx+dy*dy)
with: phi = latitude and theta = longitude
The result is in units of 60 nautical miles if theta and phi are given in degrees.
The results will be quite wrong for points that have a latitude that is much different from your base latitude, but this doesn't matter if you just want to know wich points are about 1 mile from your base.
For most programming languages you have to convert phi_base to radians (multiply by pi/180) in order to use it for cos().
(Attention: You have to take special care if your base longitude is very close to 180° or -180°, but probably that is not the case :-)
Use the calculated distances as sorting key to sort your points.
If you have to be more exact (e.g. if you want to know all points that are about 2000 miles from your home), than you must use the formula for Great Circle Distance to calculate the exact distance of two points on a sphere.
According to this link
i made working method. The answer above was wrong, because it doesn't convert lat/lng degrees to radians.
private double getDistance(double fromLat, double fromLon, double toLat, double toLon){
double radius = 6371; // Earth radius in km
double deltaLat = Math.toRadians(toLat - fromLat);
double deltaLon = Math.toRadians(toLon - fromLon);
double lat1 = Math.toRadians(fromLat);
double lat2 = Math.toRadians(toLat);
double aVal = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) +
Math.sin(deltaLon/2) * Math.sin(deltaLon/2) * Math.cos(lat1) * Math.cos(lat2);
double cVal = 2*Math.atan2(Math.sqrt(aVal), Math.sqrt(1-aVal));
double distance = radius*cVal;
Log.d("distance","radius * angle = " +distance);
return distance;
}

Categories

Resources