Android根据经纬度获取城市名的方法

根据经纬度获取当前城市名的几种方式如下(获取城市名需要网络连接)

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这个方法是耗时的,不要放在主线程中。
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值