根据经纬度获取当前城市名的几种方式如下(获取城市名需要网络连接)
1. 通过服务获取城市名
百度:
http://api.map.baidu.com/geocoder?output=json&location=39.913542,116.379763&ak=esNPFDwwsXWtsQfw4NMNmur1
google:
http://maps.google.com/maps/api/geocode/json?latlng=%2039.913542,116.379763&language=zh-CN&sensor=true
private class MyAsyncExtue extends AsyncTask<Location, Void, String> { @Override protected String doInBackground(Location... params) { HttpClient client = new DefaultHttpClient(); StringBuilder stringBuilder = new StringBuilder(); HttpGet httpGet = new HttpGet("http://api.map.baidu.com/geocoder?output=json&location=39.913542,116.379763&ak=esNPFDwwsXWtsQfw4NMNmur1"); try { HttpResponse response = client.execute(httpGet); HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String b; while ((b = bufferedReader.readLine()) != null) { stringBuilder.append(b + "\n"); } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); } @Override protected void onPostExecute(String m_list) { super.onPostExecute(m_list); Log.e("str", m_list.toString()); String city = ""; // if (m_list != null && m_list.size() > 0) { // city = m_list.get(0).getLocality();//获取城市 // } city = m_list; show_GPS.setText("城市:" + city); } }
直接用http请求这连接,就会以Json的形式返回当前的位置信息。
2.用andorid的api获取城市。
// 获取地址信息 private List<Address> getAddress(Location location) { List<Address> result = null; try { if (location != null) { Geocoder gc = new Geocoder(this, Locale.getDefault()); result = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1); } } catch (Exception e) { e.printStackTrace(); } return result; }getFromLocation这个方法是耗时的,不要放在主线程中。