Java環境下高德地圖Api的使用方式

Java高德地圖Api的使用

使用高德經緯度獲取地址信息

一些準備用到的常量

    /**
     * 高德地圖請求秘鑰
     */
    private static final String KEY = "密鑰,可以去高德地圖免費申請";
    /**
     * 返回值類型
     */
    private static final String OUTPUT = "JSON";
    /**
     * 根據地名獲取高德經緯度Api
     */
    private static final String GET_LNG_LAT_URL = "http://restapi.amap.com/v3/geocode/geo";
    /**
     * 根據高德經緯度獲取地名Api
     */
    private static final String GET_ADDRESS_URL = http://restapi.amap.com/v3/geocode/regeo;

HttpClientUtils

import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NoHttpResponseException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.nio.charset.CodingErrorAction;
import java.util.List;
import java.util.Map;
/**
 * HttpClient工具類
 */
public class HttpClientUtils {
    /**
     * 連接池最大連接數
     */
    private static final int MAX_TOTAL_CONNECTIONS = 4000;
    /**
     * 設置每個路由上的默認連接個數
     */
    private static final int DEFAULT_MAX_PER_ROUTE = 200;
    /**
     * 請求的請求超時時間 單位:毫秒
     */
    private static final int REQUEST_CONNECTION_TIMEOUT = 8 * 1000;
    /**
     * 請求的等待數據超時時間 單位:毫秒
     */
    private static final int REQUEST_SOCKET_TIMEOUT = 8 * 1000;
    /**
     * 請求的連接超時時間 單位:毫秒
     */
    private static final int REQUEST_CONNECTION_REQUEST_TIMEOUT = 5 * 1000;
    /**
     * 連接閑置多久後需要重新檢測 單位:毫秒
     */
    private static final int VALIDATE_AFTER_IN_ACTIVITY = 2 * 1000;
    /**
     * 關閉Socket時,要麼發送完所有數據,要麼等待多少秒後,就關閉連接,此時socket.close()是阻塞的 單位秒
     */
    private static final int SOCKET_CONFIG_SO_LINGER = 60;
    /**
     * 接收數據的等待超時時間,即讀超時時間,單位ms
     */
    private static final int SOCKET_CONFIG_SO_TIMEOUT = 5 * 1000;
    /**
     * 重試次數
     */
    private static int RETRY_COUNT = 5;
    /**
     * 聲明為 static volatile,會迫使線程每次讀取時作為一個全局變量讀取
     */
    private static volatile CloseableHttpClient httpClient = null;
    /**
     * @param uri
     * @return String
     * @description get請求方式
     * @author: long.he01
     */
    public static String doGet(String uri) {
        String responseBody;
        HttpGet httpGet = new HttpGet(uri);
        try {
            httpGet.setConfig(getRequestConfig());
            responseBody = executeRequest(httpGet);
        } catch (IOException e) {
            throw new RuntimeException("httpclient doGet方法異常 ", e);
        } finally {
            httpGet.releaseConnection();
        }
        return responseBody;
    }
    /**
     * @param uri
     * @param params
     * @return string
     * @description 帶map參數get請求, 此方法會將map參數拼接到連接地址上。
     */
    public static String doGet(String uri, Map<String, String> params) {
        return doGet(getGetUrlFromParams(uri, params));
    }
    /**
     * @param uri
     * @param params
     * @return String
     * @description 根據map參數拼接完整的url地址
     */
    private static String getGetUrlFromParams(String uri, Map<String, String> params) {
        List<BasicNameValuePair> resultList = FluentIterable.from(params.entrySet()).transform(
                new Function<Map.Entry<String, String>, BasicNameValuePair>() {
                    @Override
                    public BasicNameValuePair apply(Map.Entry<String, String> innerEntry) {
                        return new BasicNameValuePair(innerEntry.getKey(), innerEntry.getValue());
                    }
                }).toList();
        String paramSectionOfUrl = URLEncodedUtils.format(resultList, Consts.UTF_8);
        StringBuffer resultUrl = new StringBuffer(uri);
        if (StringUtils.isEmpty(uri)) {
            return uri;
        } else {
            if (!StringUtils.isEmpty(paramSectionOfUrl)) {
                if (uri.endsWith("?")) {
                    resultUrl.append(paramSectionOfUrl);
                } else {
                    resultUrl.append("?").append(paramSectionOfUrl);
                }
            }
            return resultUrl.toString();
        }
    }
    /**
     * @param uri
     * @param params
     * @return String
     * @description 帶map參數的post請求方法
     */
    public static String doPost(String uri, Map<String, String> params) {
        String responseBody;
        HttpPost httpPost = new HttpPost(uri);
        try {
            List<NameValuePair> nvps = Lists.newArrayList();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                nvps.add(new BasicNameValuePair(key, value));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
            httpPost.setConfig(getRequestConfig());
            responseBody = executeRequest(httpPost);
        } catch (Exception e) {
            throw new RuntimeException("httpclient doPost方法異常 ", e);
        } finally {
            httpPost.releaseConnection();
        }
        return responseBody;
    }
    /**
     * @param uri
     * @param param
     * @param contentType 根據具體請求情況指定,比如json可以是 ContentType.APPLICATION_JSON
     * @return String
     * @description 帶單string參數執行post方法
     */
    public static String doPost(String uri, String param, ContentType contentType) {
        String responseBody;
        HttpPost httpPost = new HttpPost(uri);
        try {
            StringEntity reqEntity = new StringEntity(param, contentType);
            httpPost.setEntity(reqEntity);
            httpPost.setConfig(getRequestConfig());
            responseBody = executeRequest(httpPost);
        } catch (IOException e) {
            throw new RuntimeException("httpclient doPost方法異常 ", e);
        } finally {
            httpPost.releaseConnection();
        }
        return responseBody;
    }
    /**
     * @return RequestConfig
     * @description: 獲得請求配置信息
     */
    private static RequestConfig getRequestConfig() {
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                //.setCookieSpec(CookieSpecs.DEFAULT)
                .setExpectContinueEnabled(true)
                //.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
                //.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
                .build();
        return RequestConfig.copy(defaultRequestConfig)
                .setSocketTimeout(REQUEST_CONNECTION_TIMEOUT)
                .setConnectTimeout(REQUEST_SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(REQUEST_CONNECTION_REQUEST_TIMEOUT)
                .build();
    }
    /**
     * @param method
     * @return String
     * @throws IOException
     * @description 通用執行請求方法
     */
    private static String executeRequest(HttpUriRequest method) throws IOException {
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(final HttpResponse response) throws IOException {
                int status = response.getStatusLine().getStatusCode();
                String result;
                if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
                    HttpEntity entity = response.getEntity();
                    result = entity != null ? EntityUtils.toString(entity) : null;
                    EntityUtils.consume(entity);
                    return result;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String result = getHttpClientInstance().execute(method, responseHandler);
        return result;
    }
    /**
     * @return CloseableHttpClient
     * @description 單例獲取httpclient實例
     */
    private static CloseableHttpClient getHttpClientInstance() {
        if (httpClient == null) {
            synchronized (CloseableHttpClient.class) {
                if (httpClient == null) {
                    httpClient = HttpClients.custom().setConnectionManager(initConfig()).setRetryHandler(getRetryHandler()).build();
                }
            }
        }
        return httpClient;
    }
    /**
     * @return HttpRequestRetryHandler
     * @description :獲取重試handler
     */
    private static HttpRequestRetryHandler getRetryHandler() {
        // 請求重試處理
        return new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception,
                                        int executionCount, HttpContext context) {
                if (executionCount >= RETRY_COUNT) {
                    // 假設已經重試瞭5次,就放棄
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {
                    // 假設server丟掉瞭連接。那麼就重試
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {
                    // 不要重試SSL握手異常
                    return false;
                }
                if (exception instanceof InterruptedIOException) {
                    // 超時
                    return false;
                }
                if (exception instanceof UnknownHostException) {
                    // 目標server不可達
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {
                    // 連接被拒絕
                    return false;
                }
                if (exception instanceof SSLException) {
                    // SSL握手異常
                    return false;
                }
                HttpRequest request = HttpClientContext.adapt(context).getRequest();
                // 假設請求是冪等的,就再次嘗試
                return !(request instanceof HttpEntityEnclosingRequest);
            }
        };
    }
    /**
     * @return PoolingHttpClientConnectionManager
     * @description 初始化連接池等配置信息
     */
    private static PoolingHttpClientConnectionManager initConfig() {
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(SSLContexts.createSystemDefault()))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        /**
         * 以下參數設置含義分別為:
         * 1 是否立即發送數據,設置為true會關閉Socket緩沖,默認為false
         * 2 是否可以在一個進程關閉Socket後,即使它還沒有釋放端口,其它進程還可以立即重用端口
         * 3 接收數據的等待超時時間,單位ms
         * 4 關閉Socket時,要麼發送完所有數據,要麼等待多少秒後,就關閉連接,此時socket.close()是阻塞的
         * 5 開啟監視TCP連接是否有效
         * 其中setTcpNoDelay(true)設置是否啟用Nagle算法,設置true後禁用Nagle算法,默認為false(即默認啟用Nagle算法)。
         * Nagle算法試圖通過減少分片的數量來節省帶寬。當應用程序希望降低網絡延遲並提高性能時,
         * 它們可以關閉Nagle算法,這樣數據將會更早地發 送,但是增加瞭網絡消耗。 單位為:毫秒
         */
        SocketConfig socketConfig = SocketConfig.custom()
                .setTcpNoDelay(true)
                .setSoReuseAddress(true)
                .setSoTimeout(SOCKET_CONFIG_SO_TIMEOUT)
                //.setSoLinger(SOCKET_CONFIG_SO_LINGER)
                //.setSoKeepAlive(true)
                .build();
        connManager.setDefaultSocketConfig(socketConfig);
        connManager.setValidateAfterInactivity(VALIDATE_AFTER_IN_ACTIVITY);
        ConnectionConfig connectionConfig = ConnectionConfig.custom()
                .setMalformedInputAction(CodingErrorAction.IGNORE)
                .setUnmappableInputAction(CodingErrorAction.IGNORE)
                .setCharset(Consts.UTF_8)
                .build();
        connManager.setDefaultConnectionConfig(connectionConfig);
        connManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
        connManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
        return connManager;
    }
}

GaoDeMapUtils

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class GaoDeMapUtils {
    /**
     * 高德地圖請求秘鑰
     */
    private static final String KEY = "密鑰,可以去高德地圖免費申請";
    /**
     * 返回值類型
     */
    private static final String OUTPUT = "JSON";
    /**
     * 根據地名獲取高德經緯度
     */
    private static final String GET_LNG_LAT_URL = "http://restapi.amap.com/v3/geocode/geo";
    /**
     * 根據高德經緯度獲取地名
     */
    private static final String GET_ADDRESS_URL = "http://restapi.amap.com/v3/geocode/regeo";
    /**
     * 根據高德經緯度獲取地址信息
     *
     * @param gdLon 高德地圖經度
     * @param gdLat 高德地圖緯度
     * @return
     */
    public static String getAddressByLonLat(double gdLon, double gdLat) {
        String location = gdLon + "," + gdLat;
        Map<String, String> params = new HashMap<>();
        params.put("location", location);
        // Map<String, String> result = new HashMap<>();
        try {
            // 拼裝url
            String url = jointUrl(params, OUTPUT, KEY, GET_ADDRESS_URL);
            // 調用高德SDK
            return HttpClientUtils.doPost(url, params);
            // 解析Json字符串,獲取城市名稱
            // JSONObject jsonObject = JSON.parseObject(jsonResult);
            // String regeocode = jsonObject.getString("regeocode");
            // JSONObject regeocodeObj = JSON.parseObject(regeocode);
            // String address = regeocodeObj.getString("formatted_address");
            // 組裝結果
            // result.put(location, address);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 根據地址信息獲取高德經緯度
     *
     * @param address 地址信息
     * @return
     */
    public static String getLonLarByAddress(String address) {
        Map<String, String> params = new HashMap<>();
        params.put("address", address);
        // Map<String, String> result = new HashMap<>();
        try {
            // 拼裝url
            String url = jointUrl(params, OUTPUT, KEY, GET_LNG_LAT_URL);
            // 調用高德地圖SDK
            return HttpClientUtils.doPost(url, params);
            // 解析JSON字符串,取到高德經緯度
            // JSONObject jsonObject = JSON.parseObject(jsonResult);
            // JSONArray geocodes = jsonObject.getJSONArray("geocodes");
            // String geocode = JSON.toJSONString(geocodes.get(0));
            // JSONObject geocodeObj = JSON.parseObject(geocode);
            // String lonAndLat = geocodeObj.getString("location");
            // 組裝結果
            // result.put(address, lonAndLat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 拼接請求字符串
     *
     * @param params
     * @param output
     * @param key
     * @param url
     * @return
     * @throws IOException
     */
    private static String jointUrl(Map<String, String> params, String output, String key, String url) throws IOException {
        StringBuilder baseUrl = new StringBuilder();
        baseUrl.append(url);
        int index = 0;
        Set<Map.Entry<String, String>> entrys = params.entrySet();
        for (Map.Entry<String, String> param : entrys) {
            // 判斷是否是第一個參數
            if (index == 0) {
                baseUrl.append("?");
            } else {
                baseUrl.append("&");
            }
            baseUrl.append(param.getKey()).append("=").append(URLEncoder.encode(param.getValue(), "utf-8"));
            index++;
        }
        baseUrl.append("&output=").append(output).append("&key=").append(key);
        return baseUrl.toString();
    }
}

返回結果

// 這是根據高德經緯度獲取的返回報文
{“status”:”1″,”info”:”OK”,”infocode”:”10000″,”regeocode”:{“formatted_address”:”北京市東城區東華門街道天安門”,”addressComponent”:{“country”:”中國”,”province”:”北京市”,”city”:[],”citycode”:”010″,”district”:”東城區”,”adcode”:”110101″,”township”:”東華門街道”,”towncode”:”110101001000″,”neighborhood”:{“name”:[],”type”:[]},”building”:{“name”:”天安門”,”type”:”風景名勝;風景名勝相關;旅遊景點”},”streetNumber”:{“street”:”廣場東側路”,”number”:”44號”,”location”:”116.39795,39.9097239″,”direction”:”北”,”distance”:”113.709″},”businessAreas”:[{“location”:”116.3998109423077,39.90717459615385″,”name”:”天安門”,”id”:”110101″},{“location”:”116.39981058278138,39.92383706953642″,”name”:”景山”,”id”:”110101″},{“location”:”116.4118112683418,39.91461494422115″,”name”:”王府井”,”id”:”110101″}]}}}
// 這是根據地址名稱獲取的返回報文
{“status”:”1″,”info”:”OK”,”infocode”:”10000″,”count”:”1″,”geocodes”:[{“formatted_address”:”北京市東城區天安門”,”province”:”北京市”,”citycode”:”010″,”city”:”北京市”,”district”:”東城區”,”township”:[],”neighborhood”:{“name”:[],”type”:[]},”building”:{“name”:[],”type”:[]},”adcode”:”110101″,”street”:[],”number”:[],”location”:”116.397573,39.908743″,”level”:”興趣點”}]}

Java調用高德Api獲取經緯度

1.第一步使用高德api需要先註冊高德賬號申請Key

高德開放平臺:https://lbs.amap.com/

2.第二步詳細閱讀高德api開發指南

在這裡插入圖片描述

指南地址:https://lbs.amap.com/api/webservice/guide/api/georegeo/#geo

3.編寫業務代碼

在這裡插入圖片描述

首先這裡需要判斷成功把值返回失敗默認賦值

其次筆者是使用的map形式返回值大傢也可以嘗試其他方法返回得到的值

對於最終得到的值因為是六位小數這裡是用的雙精度型存儲然後轉換為數據庫存儲值的類型按自己數據庫的類型為準

4.編寫用作調用經緯度的類

在這裡插入圖片描述

將調用得到的json格式的數據進行處理得到所需要的經緯度的值封裝入定義好的map參數中

好瞭,以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: