Home » Android » android – How to convert lat lng to a Location variable?

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

Posted by: admin May 14, 2020 Leave a comment

Questions:

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

How to&Answers:

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
})

Answer:

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