Get City Name From Location

2.2k views Asked by At

I have an app that gets Location and gets the weather in the user's city.. The weather is obtained from the city name (which should be specific). I get the Location using the following code :

    LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener locLis = new MyLocationListener();
    locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            locLis);
    Location location = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    response.setText("Last Known Location Is " + location);
    try {

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


        Geocoder geocoder = new Geocoder(MainActivity.this,Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude,longitude, 1);

        address = addresses.get(0).getAddressLine(0);
        city = addresses.get(0).getAddressLine(1);
        country = addresses.get(0).getCountryName();

        String text = "Location from Last: " + address + " ," + city + " ," + country;

        response.setText(text);

    } catch (Exception e) {
        response.setText("Location Exception : " + e);
    }

That returns "Tanta, Qesm 2" I just want "Tanta", I also tried to use addresses.get(0).getLocality() but it returns null as locality is unknown..

So, Any Idea ? :)

1

There are 1 answers

1
kamoor On

addresses.get(0).getLocality() should return locality. It return null for "Tanta, Qesm 2" means there is no locality available for this specific location.

You can also try to iterate over the list of addresses and see if locality exists.

for(Address a: addresses){
   if(a.getLocality != null){
      // take this one
   }
}