反向地理编码
上节中,我们只是获取到了当前位置的经纬度,但是很遗憾的是并不是每个人都能看懂,现在就来通过反向地理编码,将经纬度转化为我们看得懂的信息。
<span style="font-size:14px;">new Thread(new Runnable() {
@Override
public void run() {
//组装反向地理编码的接口地址
StringBuilder url=new StringBuilder();
url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng=");
url.append(location.getLatitude()).append(",");
url.append(location.getLongitude());
url.append("&sensor=false");
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(url.toString());
//在请求消息头中指定语言,保证服务器会返回中文数据
httpGet.addHeader("Accept-Language","zh-CN");
try {
HttpResponse httpResponse=httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode()==200){
HttpEntity entity=httpResponse.getEntity();
String response=EntityUtils.toString(entity,"utf-8");
JSONObject jsonObject=new JSONObject(response);
JSONArray resultArray=jsonObject.getJSONArray("results");
if (resultArray.length()>0){
JSONObject subObject=resultArray.getJSONObject(0);
String address=subObject.getString("formatted_address");
Message message=new Message();
message.what=SHOW_LOCATION;
message.obj=address;
handler.sendMessage(message);
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private Handler handler =new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case SHOW_LOCATION:
String currentPosition=(String)msg.obj;
textView.setText(currentPosition);
break;
default:
break;
}
}
};</span>