How to convert lat lng to a Location variable? - android

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

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.

How can i check if location is in my radius?

i trying to get if location is in my radius.
i.e I have my current location "LatLng" object and i have one more "LatLng" object and i want to check if the two object are in rang of 1km?
How can i implement that?
In Location.distanceBetween() function provide you distance in meters and float value ..
distanceBetween(double startLatitude, double startLongitude, double
endLatitude, double endLongitude, float[] results) Computes the
approximate distance in meters between two locations, and optionally
the initial and final bearings of the shortest path between them.
use this it working i've already checked it .....
float[] dist = new float[1];
Location.distanceBetween(firstLoaction.latitude,firstLoaction.longitude,anotherLocation.latitude,anotherLocation.longitude,dist);
if(dist[0]/1000 > 1){
//here your code or alert box for outside 1Km radius area
}
NOTE:- For getting the location distance always use Location.distanceBetween() which is provide by ANDROID .
double distanceInKiloMeters = (currentLocation.distanceTo(someLocation)) / 1000; // as distance is in meter
if(distanceInKiloMeters <= 1) {
// It is in range of 1 km
}
else {
// not in range of 1 km
}
you can try converting LatLng to Location object for both first and then using distanceTo method to find the distance between those two and check if it is 1km or not
distanceto methode to get distance from locCenter and point and just substitute this distance from the radius if <0 so the point out of range , else the point in border or inside the range.. good luck

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

find the nearest location among locations from our location

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.

Issue in setting latitude and longitude in android

I am trying to pass latitude and longitude to another activity and check the distance between this passed co-ordinates and the current co-ordinate.
In the first activity:
GeoPoint p1 = mapView.getProjection().fromPixels((int) event.getX(),(int event.getY());
setter(p1.getLatitudeE6()/ 1E6, p1.getLongitudeE6() /1E6);
public void setter(Double lati,Double longi)
{
latitude=lati;
longitude=longi;
}
on the button click event i am passing this with the help of a bundle. This works fine.
In the second activity:
public Location selected_location=null;
Double lati,longi;
Bundle b=this.getIntent().getExtras();
lati=b.getDouble("latitude");
longi=b.getDouble("longitude");
Till this much it works fine. I even printed the values. The real issue is the the lines given below:
selected_location.setLatitude(lati);
selected_location.setLongitude(longi);
I am trying to set the passed latitude and longitude values to a location variable. But this is causing the activity to terminate.
If possible please suggest a solution. If the question is childish please ignore.
If you aim to calculate only the distance you do not need to construct Location objects use this method. It is static and works with long and lat values. I can also help debuging the error if you put the stack trace of the exception.
EDIT The requested example:
float myGetDistance(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
float [] results = new float[1]; // You need only the distance, thus only one element
Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
return results[0];
}
You can complete the distance between two points given by it coordinates like this:
final float[] results= new float[1];
// The computed distance in meters is stored in results[0].
// If results has length 2 or greater, the initial bearing is stored in results[1].
// If results has length 3 or greater, the final bearing is stored in results[2].
Location.distanceBetween(refLat, refLong, latitude, longitude, results);
final float distance = results[0]; // meter!
You may reuse the results array for later computations. If you need bearing information use declare the result array of size 3, if you do not need it use size 1 and save the time for the computation of the not needed information this way.

Categories

Resources