android 根据地址获取经纬度

项目上又有个功能上传地址,然后根据上传的地址显示在地图上,但是后来发现提供的存在本地地址文件只有地名而没有经纬度,所有还要自己在讲地址转换成经纬度。

Android.location.Geocoder类提供了此功能。实际上,Geocoder既提供了前向转换,也提供了后向转换——它可以获取地址并返回经纬度,也可以将经纬度对转换为一组地址。可以通过各种方式来描述位置。例如,getFromLocationName() 方法可以获得地方的名称、物理地址和机场编号,或者该位置的流行名称。这些方法提供了一个地址列表(List<Address>),而不是一个地址。因为这些方法返回多个结果,官方建议最好提供1~5的maxResults 值来限制结果集,

 <span style="font-size:14px;">/**
     * 根据地址获取经纬度
     *
     * @param adressStr
     */
    private void getLocation(final String adressStr, final String addressMix) {
        showLoading("...");
        putAsyncTask(new Listenner() {

            @Override
            public Serializable doInBackground(String str) {
                AddressEntity addressEntity = new AddressEntity();
                List<Address> addressList = null;
                try {
                    addressList = geocoder.getFromLocationName(adressStr, 5);
                    if (addressList != null && addressList.size() > 0) {
                        addressEntity.setAddresses(addressList);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return addressEntity;
            }

            @Override
            public void onPostExecute(Serializable result, String str) {
                AddressEntity addressEntity = (AddressEntity) result;
                if (addressEntity.getAddresses() != null && addressEntity.getAddresses().size() > 0) {
                    Address address = addressEntity.getAddresses().get(0);
//                    setResult(addressMix, address.getLongitude(), address.getLatitude());
                }
                cancelLoading();
            }
        });</span>
    }

ok 转换成功,然后调用address.getLongitude();address.get
Latitude.获取到经纬度,,这样看起来好像是没什么问题,但是你会发现,有时候对输入的地址无法获取但经纬度,处理时间长,效率比较低。所以放弃了getFromLocationName方法,

用的是The Google Geocoding API

这个API整合可以代替先前的方法,输入地名返回JSON或者XML格式的文件,包含一对地址信息。

XML为http://maps.googleapis.com/maps/api/geocode/xml?address= 吉林省长春市&sensor=false吉林省长春市

JSON为http://maps.googleapis.com/maps/api/geocode/json?address=吉林省长春市&sensor=false

现在需要自己写一个静态方法去解析XML或者JSON,以JSON为例:

/**
 * 将获取到的地址转换成经纬度
 * Created by zhang on 2016/11/10.
 */
public class MapUtils {

    /**
     * @param addr 查询的地址
     * @return
     * @throws IOException
     */
    public Object[] getCoordinate(String addr) throws IOException {
        String lng = null;//经度
        String lat = null;//纬度
        String address = "";
        try {
            address = java.net.URLEncoder.encode(addr, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String key = "iQWBRMOXBiUa1WWmGONiGaOZ";
        String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStreamReader insr = null;
        BufferedReader br = null;
        try {
            httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
            if (httpsConn != null) {
                insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
                br = new BufferedReader(insr);
                String data = null;
                int count = 1;
                while ((data = br.readLine()) != null) {
                    if (count == 5) {
                        lng = (String) data.subSequence(data.indexOf(":") + 1, data.indexOf(","));//经度
                        count++;
                    } else if (count == 6) {
                        lat = data.substring(data.indexOf(":") + 1);//纬度
                        count++;
                    } else {
                        count++;
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (insr != null) {
                insr.close();
            }
            if (br != null) {
                br.close();
            }
        }
        Logger.e(this, "精度===" + lng + "=纬度===" + lat);
        return new Object[]{lng, lat};
    }
}

然后调用;注意,这里调用一定要在子线程中进行,因为网络请求时耗时操作,而主线程中是禁止执行耗时操作的。

                        new Thread() {
                            @Override
                            public void run() {
                                try {
                                    Object[] obj = new MapUtils().getCoordinate(province + city + area);
                                    if (obj != null) {
                                        setResult(location, (String) obj[0], (String) obj[1]);
                                    }else{
                                        ToastUtil.show("换个地址试试!!");
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();

    private void setResult(String strLocation, String locationX, String locationY) {
        if (TextUtils.isEmpty(strLocation)) {
            return;
        }

        Intent intent = new Intent();
        intent.putExtra("strLocation", strLocation);
        intent.putExtra("locationX", Double.valueOf(locationX).doubleValue());
        intent.putExtra("locationY", Double.valueOf(locationY).doubleValue());
        Logger.e(this, "locationX=" + locationX + "==locationY=" + locationY);
        this.setResult(TypeCodeing.TYPE_RESULTCODE_SELECT_LOCATION, intent);
        finish();
    }
ok  这样就成功的降低至转换成经纬度了。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值