I'm trying to figure out the city of where the user is using their location. Using LocationManager and Geocoder I get some nice data from the longitude and latitude, but I can't get one thing. The subAdminArea aka the city. It always returns null for me, even though everything else including the postal code is received. Is there something I am missing?
Basically this is a method I call for getting data.
public String getLocation(Locale locale, Context context, boolean city, boolean postal, boolean state_prov) throws IOException{
LocationManager locMan = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locList = new MyLocList();
Geocoder gC = new Geocoder(context,locale);
Location gpsLocation = locMan.getLastKnownLocation(locMan.GPS_PROVIDER);
locMan.requestLocationUpdates(locMan.NETWORK_PROVIDER, 500, 200, locList);
Location networkLocation = locMan.getLastKnownLocation(locMan.NETWORK_PROVIDER);
if (city)
return (gC.getFromLocation(networkLocation.getLatitude(), networkLocation.getLongitude(), 1).get(0).getSubAdminArea());
else if (postal)
return (gC.getFromLocation(networkLocation.getLatitude(), networkLocation.getLongitude(), 1).get(0).getPostalCode());
else if (state_prov)
return (gC.getFromLocation(networkLocation.getLatitude(), networkLocation.getLongitude(), 1).get(0).getAdminArea());
else
return "";
}
and the call to this method is done via:
String city = getLocation(Locale.getDefault(),getBaseContext(),true,false,false);
The only other option I have found through some research is sending a request to
http://maps.googleapis.com/maps/api/geocode/json?address=POSTALCODE&sensor=true
and it gives me a JSON of that location based on the postal code, which I can then parse, but it seems like a lot of work to find the city.
Could there be something I am missing? Or something I did wrong? I am new to location services for android.
Try this:
Geocoder gc = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gc.getFromLocation(latitude, longitude, maxResults);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < addresses.getMaxAddressLineIndex(); i++)
Log.d("=Adress=",addresses.getAddressLine(i));
}
You will get postal code, city , country, ....
I used this answer and it worked perfectly fine. It was able to get the location despite the problems I initially had in this question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.