通过百度地图API将百度坐标转换成GPS经纬度

百度地图API链接:http://developer.baidu.com/map/index.php?title=webapi/guide/changeposition

百度地图API中,有GPS坐标转百度坐标的功能 
http://dev.baidu.com/wiki/static/map/API/examples/?v=1.2&0_6#0&6 

http接口是:http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=116.397428&y=39.90923&callback=BMap.Convertor.cbk_7594 
返回结果坐标是通过base64加密的。 
这个转换算法百度是不会公开的,而且百度也没有提供百度坐标转成GPS坐标功能,这里我用了取巧的办法。 

百度坐标和GPS坐标转换在很近的距离时偏差非常接近。 
假设你有百度坐标:x1=116.397428,y1=39.90923 
把这个坐标当成GPS坐标,通过接口获得他的百度坐标:x2=116.41004950566,y2=39.916979519873 

通过计算就可以得到GPS的坐标: 
x = 2*x1-x2,y = 2*y1-y2 
x=116.38480649434001 
y=39.901480480127 

http://dev.baidu.com/wiki/static/map/API/examples/?v=1.2&0_6#0&6 将此坐标输入GPS数据项中得到的结果是:116.39743826208,39.909194650838 

实现的java代码如下:

package com.dataprocess;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CopyOfTest {
    public static void main(String args[]){
        String params = 
                "coords=114.21892734521,29.575429778924&from=1&to=5&ak=ZQU8ZGeBf95nN8wY1cNL13NP&output=json";
        
        String s=CopyOfTest.sendGet("http://api.map.baidu.com/geoconv/v1/?", params); 
        String[] s1 = s.split("\\[");
        String[] s2 = s1[1].split(",");
        String regEx ="[^0-9.\\+\\-\\s]"; 
        Pattern p = Pattern.compile(regEx); 
        Matcher m1 = p.matcher(s2[0]);
        Matcher m2 = p.matcher(s2[1]);
        String[] arrs1=m1.replaceAll("").trim().split("\\s");
        String[] arrs2=m2.replaceAll("").trim().split("\\s");
        System.out.println(s1[1]);
        System.out.println(arrs1[0]+" "+arrs2[0]);
        
    }
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url  + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    

}

同时实现读取文本中的百度经纬度坐标实现批量处理并生成gpx格式文档(可上传到openstreetmap形成轨迹)代码如下:

package com.dataprocess;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CopyOfGenerateGpx {
    public void generate(){
        String fileNames[]={"LocationData_2015-09-15",
                "LocationData_2015-09-16"
                };
        int n = fileNames.length;
        for(String fileName: fileNames){
            //输入文件
            File filein = new File("H:\\项目数据\\测试\\"+fileName+".txt");
            //输出文件
            File fileout = new File("H:\\项目数据\\测试\\gpx\\"+fileName+".gpx");
            //输出json文件
            File jsonfile = new File("H:\\项目数据\\测试\\json\\JSON_"+fileName+".json");
            try {
                //输入流
                FileInputStream fis = new FileInputStream(filein);
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader br = new BufferedReader(isr);
                //输出流
                FileOutputStream fos = new FileOutputStream(fileout);
                OutputStreamWriter osw = new OutputStreamWriter(fos);
                BufferedWriter bw = new BufferedWriter(osw);
                //json输出流
                FileOutputStream fos1 = new FileOutputStream(jsonfile);
                OutputStreamWriter osw1 = new OutputStreamWriter(fos1);
                BufferedWriter bw1 = new BufferedWriter(osw1);
                bw1.write("[\r\n");
                bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                bw.write("<gpx version=\"1.1\" creator=\"OSMTrack\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/1\""
                        + " xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\r\n");
                bw.write("<trk>\r\n<trkseg>\r\n");
                String line = null;
                String regEx ="[^0-9.\\+\\-\\s]"; 
                Pattern p = Pattern.compile(regEx); 
                while((line=br.readLine())!=null){
                    Matcher m = p.matcher(line);
                    String[] arrs=m.replaceAll("").trim().split("\\s");
                    String lonbd = arrs[2];
                    String latbd = arrs[3];
                    String params = 
                            "coords="
                            + lonbd+","+latbd
                            + "&from=1&to=5&ak=ZQU8ZGeBf95nN8wY1cNL13NP&output=json";    
                    String s=sendGet("http://api.map.baidu.com/geoconv/v1/?", params);
                    String[] s1 = s.split("\\[");
                    String[] s2 = s1[1].split(",");
                    Matcher m1 = p.matcher(s2[0]);
                    Matcher m2 = p.matcher(s2[1]);
                    String[] arrs1=m1.replaceAll("").trim().split("\\s");
                    String[] arrs2=m2.replaceAll("").trim().split("\\s");
                    System.out.println(s1[1]);
                    System.out.println(arrs1[0]+" "+arrs2[0]);
                    double lon = 2*Double.parseDouble(lonbd)-Double.parseDouble(arrs1[0]);
                    double lat = 2*Double.parseDouble(latbd)-Double.parseDouble(arrs2[0]);
                    String str = "<trkpt lat=\""+lat+"\" lon=\""+lon+"\"><ele>61.3</ele><time>2015-09-05T14:12:20Z</time></trkpt>";
                    bw.write(str+"\r\n");
                    String str1 = "{"
                            +"\"longitude\": "+lon 
                            +",\"latitude\": "+lat                   
                              +"},\r\n";
                    bw1.write(str1);
                    System.out.println(str);
                }
                bw.write("</trkseg>\r\n</trk>\r\n</gpx>\r\n");
                bw.flush();
                bw1.write("]\r\n");
                bw1.flush();
                br.close();
                fis.close();
                bw.close();
                fos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url  + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    
    public static void main(String[] args){
        CopyOfGenerateGpx g = new CopyOfGenerateGpx();
        g.generate();
    }
}

 

posted @ 2015-09-18 09:38  ~风轻云淡~  阅读(7843)  评论(0编辑  收藏  举报