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请求数据 } };
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; } };
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; }