GPS坐标 转换偏移 成百度地图 坐标

本文介绍了一种使用百度地图API实现的经纬度坐标转换方法。通过HTTP请求调用百度地图坐标转换服务,可以将标准经纬度坐标转换为百度地图专用坐标。代码示例展示了如何设置经纬度、发送请求并解析返回的JSON数据。
这个算法是国家秘密,转换需要在线连到百度进行,下面是我的苦心研究结果,快给分吧:

protected void runTest() throws Throwable {
 
    try {
        BaiduLocation bl = new BaiduLocation();
            bl.gpsx = 120;//经度
            bl.gpsy = 30;//纬度
            GetBaiduLocation(bl);
            if(bl.ok) {
                int baidux = (int)(bl.baidux*1E6);
                int baiduy = (int)(bl.baiduy*1E6);
                // 转换成功,这个坐标是百度专用的
            }
            else {
                /// 转换失败
            }
    }
    catch(Exception ex) {
    }
}
 
class BaiduLocation {
    public float gpsx, gpsy;
    public float baidux, baiduy;
    public boolean ok = false;
}
 
public static String GetBaiduLocation(float x, float y) throws MalformedURLException, IOException {
    String url = String.format("http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=%f&y=%f", x, y);
    HttpURLConnection urlConnection = (HttpURLConnection)(new URL(url).openConnection());
    urlConnection.connect();
    BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    String lines = reader.readLine();
    reader.close(); 
    urlConnection.disconnect();
    return lines;
}   
 
public static boolean GetBaiduLocation(BaiduLocation bl) {
    try {
        bl.ok = false;
        String res = GetBaiduLocation(bl.gpsx, bl.gpsy);
        if(res.startsWith("{") && res.endsWith("}")) {
            res = res.substring(1, res.length() - 2).replace("\"""");
            String[] lines = res.split(",");
            for(String line : lines) {
                String[] items = line.split(":");
                if(items.length == 2) {
                    if("error".equals(items[0])) {
                        bl.ok = "0".equals(items[1]);
                    }
                    if("x".equals(items[0])) {
                        bl.baidux = ConvertBase64(items[1]);
                    }
                    if("y".equals(items[0])) {
                        bl.baiduy = ConvertBase64(items[1]);
                    }
                }
            }
        }
    catch (Exception e) {
        bl.ok = false;
    
    return bl.ok;   
}
private static float ConvertBase64(String str) {
    byte[] bs = Base64.decode(str);       
    return Float.valueOf(new String(bs));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值