Android 框架中提供的 Geocoder API
我以前使用过Geocoding API which exists in the Android API,但它不适用于所有设备。事实上,根据我和其他人的经验,很多设备在使用 Geocoding API 时会返回 null。
出于这个原因,我选择使用反向地理编码器,它可以在所有设备上完美运行,但由于 HTTP 请求需要额外的开销。
使用反向地理编码 API 从地址中检索经度和纬度
为避免此问题,只需使用返回 JSON 对象的 Reverse Geocoding API 即可。
您可以使用API通过经纬度查找地址,也可以通过地址查找经纬度:
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false
返回:
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Pkwy",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara",
"short_name" : "Santa Clara",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.42291810,
"lng" : -122.08542120
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.42426708029149,
"lng" : -122.0840722197085
},
"southwest" : {
"lat" : 37.42156911970850,
"lng" : -122.0867701802915
}
}
},
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
在此,使用用户输入的地址向反向地理编码 API 发送 HTTP 请求,然后解析 JSON 对象以查找您需要的数据是一件简单的事情。
之前的一篇文章描述了a JSON object can be parsed from an URL.
希望这会有所帮助。