百度地图 地址转经纬度

一、文档介绍

1、格式。

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

2、请求参数。

3、返回结果参数。

4、服务状态码。

二、实例

1、引入pom.xml文件。

<properties>
    <com.alibaba.version>1.2.37</com.alibaba.version>
    <org.apache.httpcomponents.version>4.5.7</org.apache.httpcomponents.version>
</properties>
<dependencies>
    <!-- 阿里的fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>${com.alibaba.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>${org.apache.httpcomponents.version}</version>
    </dependency>
</dependencies>

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<String, Object> 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、结果。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值