Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get current location city name, android

I am writing an android application to get current location city name, I get the latitude and longitude right, but I can't get the city name. here is my code :

// To get City-Name from coordinates
String cityName = null;               
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());              
List<Address> addresses = null;  
try {  
    addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);  
    if (addresses.size() > 0)  
    System.out.println(addresses.get(0).getLocality());  
    cityName = addresses.get(0).getLocality();  
} catch (IOException e) {             
    e.printStackTrace();  
} 

String s = longitude + "\n" + latitude + "\n\nMy Currrent City is: " + cityName;
editLocation.setText(s);
like image 479
roa.tah Avatar asked Dec 02 '13 09:12

roa.tah


People also ask

How to get the current location Android?

There are two ways to get the current location of any Android device: Android's Location Manager API. Fused Location Provider: Google Play Services Location APIs.

What is Android fused location?

The fused location provider is a location API in Google Play services that intelligently combines different signals to provide the location information that your app needs.

How can I get latitude and longitude from address in Android?

The short story is you need to do: Geocoder geocoder = new Geocoder(this, Locale. getDefault()); List<Address> addresses = geocoder. getFromLocation(lat, lng, 1);


2 Answers

 public String getLocationName(double lattitude, double longitude) {

    String cityName = "Not Found";
    Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
    try {

        List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
                10);

        for (Address adrs : addresses) {
            if (adrs != null) {

                String city = adrs.getLocality();
                if (city != null && !city.equals("")) {
                    cityName = city;
                    System.out.println("city ::  " + cityName);
                } else {

                }
                // // you should also try with addresses.get(0).toSring();

            }

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

}
like image 79
naidu Avatar answered Sep 23 '22 04:09

naidu


You would have to use the geocode api in this case. This returns you a json response parse it and 'locality' is the city you require. Here is the proper documentation for it.

http://maps.google.com/maps/api/geocode/json?address=19.701989,72.774733&sensor=false

like image 44
Hardik4560 Avatar answered Sep 24 '22 04:09

Hardik4560