在我的应用程序中,用户键入一个位置,我必须获取该位置的纬度和经度。所以这里我没有 Location
对象,而是一个 String
。
我想到了使用此 String
创建 Location
对象的选项,但这是不可能的。
我知道可以使用 Google 的 places API,而且我知道如何使用它,但我更喜欢使用 SDK 中可用的任何方法。
有什么办法吗?
最佳答案
您可以使用 Geocoder .像这样:
Geocoder geocoder = new Geocoder(App.getContext(), Locale.US);
List<Address> listOfAddress;
try {
listOfAddress = geocoder.getFromLocation(theLatitude, theLongitude, 1);
if(listOfAddress != null && !listOfAddress.isEmpty()){
Address address = listOfAddress.get(0);
String country = address.getCountryCode();
String adminArea= address.getAdminArea();
String locality= address.getLocality();
}
} catch (IOException e) {
e.printStackTrace();
}
更新:从地址使用获取位置:
listOfAddress = geocoder.getFromLocationName("Address", 1);
并获取纬度、经度:
double latitude = address.getLatitude();
double longitude = address.getLongitude();
更新:当 Geocoder 返回 null 时使用此代码段获取位置:
private static final String URL = "http://maps.googleapis.com/maps/api/geocode/xml";
public static RemoteCommand getLocation(String theAddress){
RemoteCommand result = new RemoteCommand();
result.setType(Type.GET);
result.setUrl(URL);
result.addGetParam("address", theAddress);
result.addGetParam("sensor", "false");
result.addGetParam("language", "en");
// See description about GeocoderXMLHandler
result.setXmlHandler(new GeocoderXMLHandler());
return result;
}
最良好的祝愿。
关于android - 如何从位置名称获取坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17276036/