How to convert lat lng to location variable?

I am making a map application 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. However, the other location is stored as two variables: double lat, lng;

I checked the internet and found this method to help:

float distance = myLocation.distanceTo(temp);

      

The problem is that "temp" I don't have "Location", they are two different counterparts.

Is there a way to convert them to location?

PS. The code I tried but didn't work:

Location temp = null;
temp.setLatitude(23.5678);
temp.setLongitude(34.456);
float distance = location.distanceTo(temp);

      

Problem:

Null pointer access: temp variable can only be null at this location

+8


source to share


2 answers


You must create an instance Location

before you can access 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
})

      

+31


source


Alternatively, you can get the distance without instantiating the location object at all by using the static Location.distanceBetween () method .

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 [] <Strong> Results)

The calculated distance is stored in the results [0]. If results are 2 or more long, the original bearing is retained in results 1 . If the results are 3 or more long, the end bearing is stored in the results [2].

Parameters

startLatitude is the starting latitude

startLongitude start longitude

endLatitude end latitude

endLongitude end longitude

results are an array of floats to store the results

+4


source







All Articles