android中有自带的GeoCoder类,但是里面之多只能查询到XX市,详细的地址信息还是要通过调用google的GeoCoding Api来获取
首先通过定位获取当前经纬度,和1中基本一样
之后当获取到当前经纬度后开启异步任务
private LocationListener listener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
// 定位设备启用是时
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
// 定位获得信息改变时
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged");
latitudeTxt.setText("latitude:" + location.getLatitude());
longitudeTxt.setText("longitude:" + location.getLongitude());
MainActivity.location = location;
locationTask.execute();//向google请求数据
}
};
请求直接通过url拼接,注意经纬度之间不能有空格,以及最后的sensor不能少,否则返回会被拒绝。这里选择的是返回json数据。
private AsyncTask<Integer, Integer, String> locationTask = new AsyncTask<Integer, Integer, String>() {
@Override
protected void onPostExecute(String result) {
addressTxt.setText(result);
}
@Override
protected String doInBackground(Integer... params) {
String sURL = "http://maps.googleapis.com/maps/api/geocode/json?latlng="
+ location.getLatitude()
+ ","
+ location.getLongitude()
+ "&sensor=true";
try {
URL url = new URL(sURL);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
StringBuffer buff = new StringBuffer();
while ((line = reader.readLine()) != null) {
buff.append(line);
}
Log.d(TAG, buff.toString());
return jsonParams(buff.toString());//数据json解析
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
json解析没什么,不过数据很多,可以参考API给的出格式来解析https://developers.google.com/maps/documentation/geocoding/?hl=zh-cn#ReverseGeocoding。这里只解析出了详细的地址,还有地址周边的一些数据都没做解析。
private String jsonParams(String buff) {
try {
JSONObject mainObject = new JSONObject(buff);
JSONArray resultArray = mainObject.getJSONArray("results");
JSONObject resultObject = resultArray.getJSONObject(0);
String address = resultObject.getString("formatted_address");
return address;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
![](https://img-my.csdn.net/uploads/201303/08/1362748648_5495.jpg)