Search code examples
androidgoogle-maps-android-api-2

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


Solution

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