find the nearest location among locations from our location - android

I am developing an Android application.
I am getting a list of latitudes and longitudes from the server.
I have to arrange those values based on my location. I mean the nearest latitude/longitude first and then the next one etc.
I have my latitude and longitude and the list of latitude and longitudes. How can I find the nearest one?

This might not be the best way but it works :)
public static final double PI = 3.14159265;
public static final double deg2radians = PI/180.0;
public static final double miles = 0.000621371192;
public static final double kms = 0.001;
public static double getDistance(double latitude1, double longitude1, double latitude2,double longitude2) {
double distance;
Location locationA = new Location("point A");
locationA.setLatitude(latitude1);
locationA.setLongitude(longitude1);
Location locationB = new Location("point B");
locationB.setLatitude(latitude2);
locationB.setLongitude(longitude2);
distance = locationA.distanceTo(locationB);
double radd = distance * kms;
return radd;
}

pseudo code :
location.distanceTo(locFromServer);
and for the sorting
Colection.sort(listOfLocations;new Comparator(){
compareTo(){
// location.distanceTo(locFromServer)
}
}

You can simply calculate the distances of the user's position to the downloaded locations, and select the smallest one.
Have a look here: Quicker way to calculate geographic distance between two points.

Related

How to make a custom adapter to retrieve from firebase database and sort on the client side and then populate adapter

I've lat and lng stored in the firebase database. Now I want to retrieve these and then calculate the distance between my current location and those points and then sort them in increasing order of distance in the adapter
I am able to retrieve the lat and lng and calculate distance and populate the firebase recyclerview adapter. But in this adapter, the items are not sorted according to the distance. I want to sort them according to the distance calculated after retrieving the item.
Code in FirebaseRecyclerAdapter inside onBindViewHolder
lat = mLastLocation.getLatitude();
lng = mLastLocation.getLongitude();
lat1 = Double.parseDouble(model.getMylat());
lng1 = Double.parseDouble(model.getMylng());
loadLocationForThisUser(lat, lng, lat1, lng1);
holder.txt_distance.setText(distance);
And code to calculate the distance
private void loadLocationForThisUser(Double lat, Double lng, Double lat1, Double lng1) {
//Create location from user coordinates
currentUser1 = new Location("");
currentUser1.setLatitude(lat);
currentUser1.setLongitude(lng);
//Create location from friend coordinates
friend1 = new Location("");
friend1.setLatitude(lat1);
friend1.setLongitude(lng1);
distanceNumeric = (int) (currentUser1.distanceTo(friend1)/1000);
Log.i("distanceNumeric", String.valueOf(distanceNumeric));
distance = (new
DecimalFormat("#.#").format((currentUser1.distanceTo(friend1)) / 1000)+ "
kms");
}
Currently, the output is items being populated without any order of sorting based on the distance calculated. I'm expecting the adapter to be populated with items in increasing order of distance that has been calculated.

Why does Android location.distanceTo return values in Millions?

In my Android application I am trying to calculate the distance between two locations but the values I am getting is in tens of Millions 11Million+. The actual distance between the two point/location is just 1.1km - 1.3Km. Why is this so? Even if the value the .distanceTo method returns is in meters 11M meters is still a very big value.
Here is my code:
Location locationA = new Location("LocationA");
locationA.setLatitude(lat);
locationA.setLongitude(lang);
Location locationB = new Location("LocationB");
locationB.setLatitude(14.575224);
locationB.setLongitude(121.042475);
float distance = locationA.distanceTo(locationB);
BigDecimal _bdDistance;
_bdDistance = round(distance,2);
String _strDistance = _bdDistance.toString();
Toast.makeText(this, "distance between two locations = "+_strDistance, Toast.LENGTH_SHORT).show();
public static BigDecimal round(float d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd;
}
Your approximation is right. It returns the distance in meters.
You can convert it to KM by dividing it by 1000 like so;
float distance = locationA.distanceTo(locationB)/1000;
Read more about distanceTo here.
here in my screenshot you can see, if we take location from double latitude, longitude i.e. 6 digit after decimal but actually Location hold latitude value till 8 digits. The main difference is here. So don't use double for storing latitude, longitude. Try to use anotherway

How to calculate distance between set of Latitudes and Longitudes in android?

I'm trying to calculate distance between LatLng points. It's easy to calculate for two coordinates. I have to calculate distance between more than two LatLngs and calculate the cumulative distance from a set of LatLngs. I calculated distance between two points as per the following code.
tvDistance=(TextView)findViewById(R.id.textView4);
Location loc1=new Location("");
loc1.setLatitude(11.2805);
loc1.setLongitude(77.5989);
Location loc2=new Location("");
loc2.setLatitude(11.2801);
loc2.setLongitude(77.5976);
DecimalFormat format=new DecimalFormat("#.##");
double distanceInMeters = loc1.distanceTo(loc2)/1000;
tvDistance.setText(format.format(distanceInMeters) + " Km's");
Now I have for example sixteen LatLng points. First is starting place and last is stopping place. I have the LatLngs in a ArrayList. tried the following code. But it caused ArrayIndexOutOfBoundException.
Do anybody know a method please share with me. Thanks.
private void calculateDistance() {
for (int i=0;i<coordList.size();i++){
LatLng l1=coordList.get(i);
double lat1=l1.latitude;
double lng1=l1.longitude;
Location location1=new Location("");
location1.setLatitude(lat1);
location1.setLongitude(lng1);
LatLng l2=coordList.get(i+1);
double lat2=l2.latitude;
double lng2=l2.longitude;
Location location2=new Location("");
location2.setLatitude(lat2);
location2.setLongitude(lng2);
DecimalFormat format=new DecimalFormat("#.##");
double distance=location1.distanceTo(location2)/1000;
Toast.makeText(MainPage.this,format.format(distance) + " Km's",Toast.LENGTH_SHORT).show();
}
}
You can use SphericalUtil.computeLength method:
http://googlemaps.github.io/android-maps-utils/javadoc/com/google/maps/android/SphericalUtil.html#computeLength-java.util.List-
Sources: https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/SphericalUtil.java
The line
LatLng l2=coordList.get(i+1);
causes the exception.
jon
->Its easy to calculate the distance if you have sets of latitudes and longitudes
ArrayList<RideRoutes> ride_route_list = new ArrayList<>();
//suppose "ride_route_list" contains collections of Latitudes and longitudes
String distance_covered_str;
double total_meters = 0.0;
for(int i = 0; i < (ride_route_list.size() - 1); i++){
double previous_latitude = Double.parseDouble(ride_route_list.get(i).getRout_latitude());
double previous_longitude = Double.parseDouble(ride_route_list.get(i).getRout_longitude());
double updated_latitude = Double.parseDouble(ride_route_list.get(i+1).getRout_latitude());
double updated_longitude = Double.parseDouble(ride_route_list.get(i+1).getRout_longitude());
Location start_latlng = new Location("location_previous");
start_latlng.setLatitude(previous_latitude);
start_latlng.setLongitude(previous_longitude);
Location end_latlng = new Location("location_updated");
end_latlng.setLatitude(updated_latitude);
end_latlng.setLongitude(updated_longitude);
total_meters += start_latlng.distanceTo(end_latlng);
}
double distance_covered_km = total_meters / 1000;
distance_covered_str = String.format(Locale.getDefault(), "%.2f", distance_covered_km);
Note:
->here ride_route_list is an ArrayList which contains the list of Latitude and longitude
RideRoutes Class Structure:
public class RideRoutes {
private String rout_latitude;
private String rout_longitude;
public RideRoutes(String rout_latitude, String rout_longitude) {
this.rout_latitude = rout_latitude;
this.rout_longitude = rout_longitude;
}
public String getRout_latitude() {
return rout_latitude;
}
public void setRout_latitude(String rout_latitude) {
this.rout_latitude = rout_latitude;
}
public String getRout_longitude() {
return rout_longitude;
}
public void setRout_longitude(String rout_longitude) {
this.rout_longitude = rout_longitude;
}
}

Running gps android

Trying to create a running gps in android, using this code to calculate the distance between two points every second (at least that's what I think it's doing):
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
final Handler h = new Handler();
final int delay = 1000; //milliseconds
h.postDelayed(new Runnable() {
public void run() {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Location locationA = new Location("point A");
final Location locationB = new Location("point B");
locationA.setLatitude(latitude);
locationA.setLongitude(longitude);
Timer t = new Timer();
h.postDelayed(new Runnable() {
public void run() {
double latitude1 = gps.getLatitude();
double longitude2 = gps.getLongitude();
locationB.setLatitude(latitude1);
locationB.setLongitude(longitude2);
}
}, delay);
float distance = locationA.distanceTo(locationB);
finalDistance[0] = (finalDistance[0] + distance);
displayDistance.setText(String.valueOf(finalDistance[0]));
h.postDelayed(this, delay);
}
}, delay);
The distance changes more or less by the same increment whether I'm walking or not walking.
The distance I get is also a weird value, e.g.: 6.47875890357E9
My questions: 1)What unit is this distance in?
2)Am I getting some random gobbledigook because of crap programming skills?
1) The units are meters (see distanceTo()).
2) Yes. But like all programmers, you're still learning, so to be more helpful I won't just leave it there! The reason you are getting a huge distance is because your code is getting the distance between locationA and locationB, and you haven't set locationB at the time you execute the line:
float distance = locationA.distanceTo(locationB);
So you're getting the distance between locationA and lat/long 0,0.
You're only setting the latitude and longitude of locationB in your Runnable which will be executed after distance has been set. So, you probably need to move your distance calculation and the code that outputs it to within your Runnable that sets the latitude and longitude for locationB. You'll also have to make locationA final to do that.

How to convert lat lng to a Location variable?

I am making a map app in android, I want to get 2 locations on the map, and see the distance between them. I already got my current location as a "Location" variable. The other place however is saved as two variables : double lat,lng;
I have checked the internet and found this method that will help :
float distance = myLocation.distanceTo(temp);
The problem is that the "temp" I have is not a "Location", it is 2 different doubles.
Is there a way to convert them to Location?
PS. Code i tried but did't work :
Location temp = null;
temp.setLatitude(23.5678);
temp.setLongitude(34.456);
float distance = location.distanceTo(temp);
Problem :
Null pointer access: The variable temp can only be null at this location
You have to instantiate Location, before accessing its members. For example
Java
Location temp = new Location(LocationManager.GPS_PROVIDER);
temp.setLatitude(23.5678);
temp.setLongitude(34.456);
float distance = location.distanceTo(temp);
Kotlin
val distance = location.distanceTo(Location(LocationManager.GPS_PROVIDER).apply {
latitude = 23.5678
longitude = 34.456
})
Alternatively, you can get the distance without instantiating a Location object at all using the static method Location.distanceBetween().
float[] results = new float[1];
Location.distanceBetween(1, 2, 2 , 2, results);
public static void distanceBetween (double startLatitude, double
startLongitude, double endLatitude, double endLongitude, float[]
results)
The computed distance is stored in results[0]. If results has length 2
or greater, the initial bearing is stored in results1. If results
has length 3 or greater, the final bearing is stored in results[2].
Parameters
startLatitude the starting latitude
startLongitude the starting longitude
endLatitude the ending latitude
endLongitude the ending longitude
results an array of floats to hold the results

Categories

Resources