无法使用Geocoder获取状态。在堆栈中尝试了很多方法,但没有解决方案。是否可以使用Geocoder。我也尝试过使用http://maps.googleapis.com/maps/api/geocode/json?latlng=22.,88&sensor=true&key=
,但是它返回的是json但不是直接返回State。为了获取状态,我需要解析完整的json。有没有简单的解决方法
这是最常用的方法,但返回null
public void getAdressFromLatlng1(Double lat,Double lng) {
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(context, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lng, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
Log.d("Coordinates",lat+""+lng);
if(addresses!=null && addresses.size()>0) {
String state=addresses.get(0).getAdminArea();
Log.d("State",state);
}
}
也尝试过此操作,但也返回null:
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
strReturnedAddress.append(returnedAddress.getAddressLine(0)).append("\n");
String cityName = "", stateName = "", countryName = "", zipCode = "";
if (!TextUtils.isEmpty(addresses.get(0).getLocality()) /*&& !isFromFilter*/) {
prefs.setString(Prefs.PREFS_KEY_SETTINGS_CITY, addresses.get(0).getLocality());
prefs.setString(Prefs.PREFS_KEY_CITY, addresses.get(0).getLocality());
}
if (!TextUtils.isEmpty(addresses.get(0).getAdminArea()) /*&& !isFromFilter*/) {
prefs.setString(Prefs.PREFS_KEY_SETTING_STATE, addresses.get(0).getAdminArea());
prefs.setString(Prefs.PREFS_KEY_STATE, addresses.get(0).getAdminArea());
}
if (!TextUtils.isEmpty(addresses.get(0).getCountryName()) /*&& !isFromFilter*/) {
prefs.setString(Prefs.PREFS_KEY_SETTINGS_COUNTRY, addresses.get(0).getCountryName());
prefs.setString(Prefs.PREFS_KEY_COUNTRY, addresses.get(0).getCountryName());
}
if (!TextUtils.isEmpty(addresses.get(0).getPostalCode()) /*&& !isFromFilter*/)
prefs.setString(Prefs.PREFS_KEY_SETTING_ZIP, addresses.get(0).getPostalCode());
/*strReturnedAddress.append(addresses.get(0).getLocality()).append("\n");//City
strReturnedAddress.append(addresses.get(0).getAdminArea()).append("\n");//State
strReturnedAddress.append(addresses.get(0).getCountryName()).append("\n");//Country
strReturnedAddress.append(addresses.get(0).getPostalCode());//Zip Code
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}*/
strAdd = strReturnedAddress.toString();
Log.w("address", "" + strReturnedAddress.toString());
} else {
Log.w("address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("address", "Canont get Address!");
Toast.makeText(this, getString(R.string.error_get_address), Toast.LENGTH_SHORT).show();
}
return strAdd;
}