Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get coordinates from a location name

In my app user types a location and I have to get latitude and longitude for that location. So here I don't have Location object but a String.

I thought of an option to create a Location object using this String but it is not possible.

I know using Google's places API it is possible and I know how to use that, but I prefer using any method available in SDK.

Is there any way to do so?

like image 784
Geek Avatar asked Feb 16 '23 03:02

Geek


1 Answers

You can use Geocoder. Like this :

Geocoder geocoder = new Geocoder(App.getContext(), Locale.US);
    List<Address> listOfAddress;
    try {
        listOfAddress = geocoder.getFromLocation(theLatitude, theLongitude, 1);
        if(listOfAddress != null && !listOfAddress.isEmpty()){
        Address address = listOfAddress.get(0);

        String country = address.getCountryCode();
        String adminArea= address.getAdminArea();
        String locality= address.getLocality();

    }
    } catch (IOException e) {
        e.printStackTrace();
    }

Updated : to get location from address use :

listOfAddress = geocoder.getFromLocationName("Address", 1);

and to get lat, lon :

double latitude = address.getLatitude();
double longitude = address.getLongitude();

Updated : using this snippet to get Location when Geocoder returns null:

private static final String URL = "http://maps.googleapis.com/maps/api/geocode/xml";

public static RemoteCommand getLocation(String theAddress){
    RemoteCommand result = new RemoteCommand();

    result.setType(Type.GET);
    result.setUrl(URL);
    result.addGetParam("address", theAddress);
    result.addGetParam("sensor", "false");
    result.addGetParam("language", "en");

    // See description about GeocoderXMLHandler
    result.setXmlHandler(new GeocoderXMLHandler());

    return result;
}

Best wishes.

like image 130
Yakiv Mospan Avatar answered Feb 28 '23 08:02

Yakiv Mospan