How to convert lat lng to a Location variable?
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