Chr*_*tis 15 android location coordinates
我想从一个地址获取一个地方的纬度和经度.我不想从GPS或网络中获得经度和纬度.
我希望用户能够在TextView中输入他想要的地址(例如他的办公室)和文本字段下方的一些建议,就像在Google地图应用中输入地址一样.然后我想检索给定地址的坐标.
如果无法做到这一点,有办法通过谷歌地图应用程序本身获取地址.也许我可以从我的应用程序调用gmaps,用户将键入地址,gmaps将返回坐标.
我该怎么做?
Dem*_*ian 16
Android框架中提供的Geocoder API
我之前使用的是Geocoding API,它存在于Android API中,但它并不适用于所有设备.事实上,根据我和其他人的经验,许多设备在使用Geocoding API时将返回null.
出于这个原因,我选择使用反向地理编码器,它可以在所有设备上完美运行,但由于HTTP请求需要额外的开销.
使用反向地理编码API从地址中检索经度和纬度
为了避免这个问题,使用返回JSON对象的反向地理编码API很简单.
您可以使用API通过纬度和经度查找地址,也可以从地址中查找纬度和经度:
返回:
{
"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"
}
Run Code Online (Sandbox Code Playgroud)
因此,向反向地理编码API发送HTTP请求的简单问题是用户输入的地址,然后解析JSON对象以找到所需的数据.
上一篇文章描述了如何从URL解析JSON对象.
希望这可以帮助.
您可以使用以下方法:
Geocoder coder = new Geocoder(this);
try {
ArrayList<Address> adresses = (ArrayList<Address>) coder.getFromLocationName("Your Address", 50);
for(Address add : adresses){
if (statement) {//Controls to ensure it is right address such as country etc.
double longitude = add.getLongitude();
double latitude = add.getLatitude();
}
}
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)