我正在尝试获取用户当前位置的邮政编码。我在MyActivity中有一个teditText,应根据我从此活动获得的邮政编码进行填充。
public class LocationActivity extends MyActivity {
double LATITUDE;
double LONGITUDE;
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
{
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedZip = addresses.get(0);
StringBuilder currentZip = new StringBuilder("Address:\n");
for(int i=0; i<returnedZip.getMaxAddressLineIndex(); i++) {
strcurrentZip.append(returnedZip.getPostalCode());
}
m_zip.setText(strcurrentZip.toString());
}
else {
m_zip.setText("No zip returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
m_zip.setText("zip not found!");
}
}
}
我没有收到任何回复,app logcat没有显示任何错误,但我要填充的editText字段仍为空白。
答案 0 :(得分:3)
这里......
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//GeocodeResponse/result/address_component[type=\"postal_code\"]/long_name/text()";
InputSource inputSource = new InputSource("https://maps.googleapis.com/maps/api/geocode/xml?latlng="+VARIABLECONTAININGLATITUDE+","+VARIABLECONTAININGLONGITUDE+"&sensor=true");
String zipcode = (String) xpath.evaluate(expression, inputSource, XPathConstants.STRING);
其中VARIABLECONTAININGLATITUDE和VARIABLECONTAININGLONGITUDE是来自GPS或您选择的任何位置提供商的纬度和经度。
您还需要在清单
中的清单和位置权限中获得互联网许可答案 1 :(得分:1)
请在下面写下获取邮政编码的代码
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(currentlat, currentlng, 1);
现在地址列表包含最近的已知区域。 Address对象具有getPostalCode()函数。抓住第一个对象,找到它的邮政编码。