您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Java環(huán)境中高德地圖Api怎么用,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
一些準(zhǔn)備用到的常量
/** * 高德地圖請(qǐng)求秘鑰 */ private static final String KEY = "密鑰,可以去高德地圖免費(fèi)申請(qǐng)"; /** * 返回值類型 */ private static final String OUTPUT = "JSON"; /** * 根據(jù)地名獲取高德經(jīng)緯度Api */ private static final String GET_LNG_LAT_URL = "http://restapi.amap.com/v3/geocode/geo"; /** * 根據(jù)高德經(jīng)緯度獲取地名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 { /** * 連接池最大連接數(shù) */ private static final int MAX_TOTAL_CONNECTIONS = 4000; /** * 設(shè)置每個(gè)路由上的默認(rèn)連接個(gè)數(shù) */ private static final int DEFAULT_MAX_PER_ROUTE = 200; /** * 請(qǐng)求的請(qǐng)求超時(shí)時(shí)間 單位:毫秒 */ private static final int REQUEST_CONNECTION_TIMEOUT = 8 * 1000; /** * 請(qǐng)求的等待數(shù)據(jù)超時(shí)時(shí)間 單位:毫秒 */ private static final int REQUEST_SOCKET_TIMEOUT = 8 * 1000; /** * 請(qǐng)求的連接超時(shí)時(shí)間 單位:毫秒 */ private static final int REQUEST_CONNECTION_REQUEST_TIMEOUT = 5 * 1000; /** * 連接閑置多久后需要重新檢測(cè) 單位:毫秒 */ private static final int VALIDATE_AFTER_IN_ACTIVITY = 2 * 1000; /** * 關(guān)閉Socket時(shí),要么發(fā)送完所有數(shù)據(jù),要么等待多少秒后,就關(guān)閉連接,此時(shí)socket.close()是阻塞的 單位秒 */ private static final int SOCKET_CONFIG_SO_LINGER = 60; /** * 接收數(shù)據(jù)的等待超時(shí)時(shí)間,即讀超時(shí)時(shí)間,單位ms */ private static final int SOCKET_CONFIG_SO_TIMEOUT = 5 * 1000; /** * 重試次數(shù) */ private static int RETRY_COUNT = 5; /** * 聲明為 static volatile,會(huì)迫使線程每次讀取時(shí)作為一個(gè)全局變量讀取 */ private static volatile CloseableHttpClient httpClient = null; /** * @param uri * @return String * @description get請(qǐng)求方式 * @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參數(shù)get請(qǐng)求, 此方法會(huì)將map參數(shù)拼接到連接地址上。 */ public static String doGet(String uri, Map<String, String> params) { return doGet(getGetUrlFromParams(uri, params)); } /** * @param uri * @param params * @return String * @description 根據(jù)map參數(shù)拼接完整的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參數(shù)的post請(qǐng)求方法 */ 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 根據(jù)具體請(qǐng)求情況指定,比如json可以是 ContentType.APPLICATION_JSON * @return String * @description 帶單string參數(shù)執(zhí)行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: 獲得請(qǐng)求配置信息 */ 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 通用執(zhí)行請(qǐng)求方法 */ 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實(shí)例 */ 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() { // 請(qǐng)求重試處理 return new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= RETRY_COUNT) { // 假設(shè)已經(jīng)重試了5次,就放棄 return false; } if (exception instanceof NoHttpResponseException) { // 假設(shè)server丟掉了連接。那么就重試 return true; } if (exception instanceof SSLHandshakeException) { // 不要重試SSL握手異常 return false; } if (exception instanceof InterruptedIOException) { // 超時(shí) return false; } if (exception instanceof UnknownHostException) { // 目標(biāo)server不可達(dá) return false; } if (exception instanceof ConnectTimeoutException) { // 連接被拒絕 return false; } if (exception instanceof SSLException) { // SSL握手異常 return false; } HttpRequest request = HttpClientContext.adapt(context).getRequest(); // 假設(shè)請(qǐng)求是冪等的,就再次嘗試 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); /** * 以下參數(shù)設(shè)置含義分別為: * 1 是否立即發(fā)送數(shù)據(jù),設(shè)置為true會(huì)關(guān)閉Socket緩沖,默認(rèn)為false * 2 是否可以在一個(gè)進(jìn)程關(guān)閉Socket后,即使它還沒(méi)有釋放端口,其它進(jìn)程還可以立即重用端口 * 3 接收數(shù)據(jù)的等待超時(shí)時(shí)間,單位ms * 4 關(guān)閉Socket時(shí),要么發(fā)送完所有數(shù)據(jù),要么等待多少秒后,就關(guān)閉連接,此時(shí)socket.close()是阻塞的 * 5 開(kāi)啟監(jiān)視TCP連接是否有效 * 其中setTcpNoDelay(true)設(shè)置是否啟用Nagle算法,設(shè)置true后禁用Nagle算法,默認(rèn)為false(即默認(rèn)啟用Nagle算法)。 * Nagle算法試圖通過(guò)減少分片的數(shù)量來(lái)節(jié)省帶寬。當(dāng)應(yīng)用程序希望降低網(wǎng)絡(luò)延遲并提高性能時(shí), * 它們可以關(guān)閉Nagle算法,這樣數(shù)據(jù)將會(huì)更早地發(fā) 送,但是增加了網(wǎng)絡(luò)消耗。 單位為:毫秒 */ 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 { /** * 高德地圖請(qǐng)求秘鑰 */ private static final String KEY = "密鑰,可以去高德地圖免費(fèi)申請(qǐng)"; /** * 返回值類型 */ private static final String OUTPUT = "JSON"; /** * 根據(jù)地名獲取高德經(jīng)緯度 */ private static final String GET_LNG_LAT_URL = "http://restapi.amap.com/v3/geocode/geo"; /** * 根據(jù)高德經(jīng)緯度獲取地名 */ private static final String GET_ADDRESS_URL = "http://restapi.amap.com/v3/geocode/regeo"; /** * 根據(jù)高德經(jīng)緯度獲取地址信息 * * @param gdLon 高德地圖經(jīng)度 * @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); // 調(diào)用高德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"); // 組裝結(jié)果 // result.put(location, address); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 根據(jù)地址信息獲取高德經(jīng)緯度 * * @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); // 調(diào)用高德地圖SDK return HttpClientUtils.doPost(url, params); // 解析JSON字符串,取到高德經(jīng)緯度 // 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"); // 組裝結(jié)果 // result.put(address, lonAndLat); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 拼接請(qǐng)求字符串 * * @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) { // 判斷是否是第一個(gè)參數(shù) 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(); } }
返回結(jié)果
// 這是根據(jù)高德經(jīng)緯度獲取的返回報(bào)文
{"status":"1","info":"OK","infocode":"10000","regeocode":{"formatted_address":"北京市東城區(qū)東華門(mén)街道天安門(mén)","addressComponent":{"country":"中國(guó)","province":"北京市","city":[],"citycode":"010","district":"東城區(qū)","adcode":"110101","township":"東華門(mén)街道","towncode":"110101001000","neighborhood":{"name":[],"type":[]},"building":{"name":"天安門(mén)","type":"風(fēng)景名勝;風(fēng)景名勝相關(guān);旅游景點(diǎn)"},"streetNumber":{"street":"廣場(chǎng)東側(cè)路","number":"44號(hào)","location":"116.39795,39.9097239","direction":"北","distance":"113.709"},"businessAreas":[{"location":"116.3998109423077,39.90717459615385","name":"天安門(mén)","id":"110101"},{"location":"116.39981058278138,39.92383706953642","name":"景山","id":"110101"},{"location":"116.4118112683418,39.91461494422115","name":"王府井","id":"110101"}]}}}
// 這是根據(jù)地址名稱獲取的返回報(bào)文
{"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"北京市東城區(qū)天安門(mén)","province":"北京市","citycode":"010","city":"北京市","district":"東城區(qū)","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"110101","street":[],"number":[],"location":"116.397573,39.908743","level":"興趣點(diǎn)"}]}
高德開(kāi)放平臺(tái):https://lbs.amap.com/
指南地址:https://lbs.amap.com/api/webservice/guide/api/georegeo/#geo
首先這里需要判斷成功把值返回失敗默認(rèn)賦值
其次筆者是使用的map形式返回值大家也可以嘗試其他方法返回得到的值
對(duì)于最終得到的值因?yàn)槭橇恍?shù)這里是用的雙精度型存儲(chǔ)然后轉(zhuǎn)換為數(shù)據(jù)庫(kù)存儲(chǔ)值的類型按自己數(shù)據(jù)庫(kù)的類型為準(zhǔn)
將調(diào)用得到的json格式的數(shù)據(jù)進(jìn)行處理得到所需要的經(jīng)緯度的值封裝入定義好的map參數(shù)中
關(guān)于“Java環(huán)境中高德地圖Api怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。