百度地图 地址转经纬度

一、文档介绍

1、格式。

http://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation //GET请求

2、请求参数。

百度地图 地址转经纬度_第1张图片

3、返回结果参数。

百度地图 地址转经纬度_第2张图片

4、服务状态码。

百度地图 地址转经纬度_第3张图片

二、实例

1、引入pom.xml文件。


    1.2.37
    4.5.7


    
    
        com.alibaba
        fastjson
        ${com.alibaba.version}
    
    
        org.apache.httpcomponents
        httpclient
        ${org.apache.httpcomponents.version}
    

2、创建http工具类。

package com.zxj.reptile.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

public class HttpUtils {
    private static String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36";
    public static final int timeOut = 9000;
    private static final String GET = "GET";
    private static final String POST = "POST";

    public interface CallBack {
        void onRequestComplete(String var1);
    }

    public static void doGetAsyn(final String urlStr, final HttpUtils.CallBack callBack) {
        (new Thread(() -> {
            try {
                String result = HttpUtils.doGet(urlStr);
                if (callBack != null) {
                    callBack.onRequestComplete(result);
                }
            } catch (Exception var2) {
                var2.printStackTrace();
            }

        })).start();
    }

    public static void doPostAsyn(final String urlStr, final String params, final HttpUtils.CallBack callBack) throws Exception {
        (new Thread(() -> {
            try {
                String result = HttpUtils.doPost(urlStr, params);
                if (callBack != null) {
                    callBack.onRequestComplete(result);
                }
            } catch (Exception var2) {
                var2.printStackTrace();
            }

        })).start();
    }

    public static String doGet(String urlStr) {
        HttpURLConnection conn = null;
        InputStream is = null;
        BufferedReader bufferedReader = null;
        String result = "";
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(timeOut);
            conn.setConnectTimeout(timeOut);
            conn.setRequestMethod(GET);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("charset", "utf-8");
            conn.setRequestProperty("user-agent", userAgent);
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("responseCode is not 200 ...");
            }
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8")));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return result;
    }

    public static String doPost(String urlStr, String jsonString) {
        PrintWriter out = null;
        BufferedReader bufferedReader = null;
        String result = "";
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(timeOut);
            conn.setConnectTimeout(timeOut);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("charset", "utf-8");
            conn.setRequestProperty("user-agent", userAgent);
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            if (jsonString != null && !jsonString.trim().equals("")) {
                out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), Charset.forName("UTF-8")));
                out.print(jsonString);
                out.flush();
            }
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("responseCode is not 200 ...");
            }
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8")));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String postRequest(String url, Map param) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        String parameter = JSON.toJSONString(param);
        StringEntity se = new StringEntity(parameter, Charset.forName("UTF-8"));
        se.setContentType("application/json");
        se.setContentEncoding("UTF-8");
        httpPost.setEntity(se);
        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, "UTF-8");
    }
}

3、创建百度地图的类。

package com.zxj.reptile.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class BaiduMapUtils {
    private static final String key = "mqG02Ch1FvDobisfBP5VhUlTYQZDdBr4";

    public static JSONObject getGeocode(String address) throws Exception {
        JSONObject location = null;
        String url = String.format("http://api.map.baidu.com/geocoder?address=%s&key=%s&output=json", address, key);
        String result = HttpUtils.doGet(url);
        if (result != null) {
            JSONObject resultData = JSON.parseObject(result);
            if (resultData.get("status").equals("OK")) {
                location = (JSONObject) ((JSONObject) resultData.get("result")).get("location");
            }
        }
        return location;
    }
}

4、创建测试类。

package com.zxj.reptile.test;

import com.alibaba.fastjson.JSONObject;
import com.zxj.reptile.utils.BaiduMapUtils;

import java.math.BigDecimal;

public class Test {
    public static void main(String[] args) {
        try {
            String longitude = null, latitude = null;
            JSONObject location = BaiduMapUtils.getGeocode("霞浦县");
            if (location.get("lng") != null) {
                BigDecimal lng = (BigDecimal) location.get("lng");
                longitude = lng.toString();
            }
            if (location.get("lat") != null) {
                BigDecimal lat = (BigDecimal) location.get("lat");
                latitude = lat.toString();
            }
            System.out.println("经度:" + longitude);
            System.out.println("纬度:" + latitude);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5、结果。

百度地图 地址转经纬度_第4张图片

 

你可能感兴趣的:(百度地图)