Android框架中提供的地理编码器API
我之前使用过Android API中存在的地理编码API,但它并不适用于所有设备。实际上,根据我的和其他人的经验,许多设备在使用地理编码API时会返回null。
因此,我选择使用反向地理编码器,它在所有设备上都可以完美运行,但由于HTTP请求需要额外的开销。
使用反向地理编码API从地址检索经度和纬度
为了避免这个问题,只需简单地使用反向地理编码API即可返回JSON对象。
您可以使用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对象以找到所需的数据即可。
之前的一篇文章描述了如何从URL中解析JSON对象。
希望这可以帮助您。