使用Java和高德地圖API將經(jīng)緯度轉(zhuǎn)換為地理位置信息的步驟
前言
在開發(fā)涉及地圖和位置服務(wù)的應(yīng)用時(shí),將GPS設(shè)備提供的經(jīng)緯度坐標(biāo)轉(zhuǎn)換成人類可讀的地理位置是一個(gè)常見需求。本文將詳細(xì)介紹如何使用Java語言和高德地圖API實(shí)現(xiàn)這一功能,包括環(huán)境準(zhǔn)備、代碼實(shí)現(xiàn)、異常處理以及代碼優(yōu)化。
開發(fā)環(huán)境準(zhǔn)備
- Java環(huán)境:確保你的開發(fā)環(huán)境中已安裝Java。
- 高德地圖API密鑰:訪問高德地圖開放平臺(tái),注冊并申請API密鑰。
步驟一:創(chuàng)建Java類
首先,創(chuàng)建一個(gè)名為LocationFinder
的Java類。這個(gè)類包含一個(gè)主方法main
用于調(diào)用位置轉(zhuǎn)換功能,并且包含getLocationFromCoordinates
方法用于實(shí)現(xiàn)經(jīng)緯度到地理位置的轉(zhuǎn)換。
public class LocationFinder { public static void main(String[] args) { String longitude = "115.658755"; // 經(jīng)度 String latitude = "38.961134"; // 緯度 String apiKey = "您的API密鑰"; // 高德地圖API密鑰 try { String location = getLocationFromCoordinates(longitude, latitude, apiKey); System.out.println("地理位置: " + location); } catch (Exception e) { e.printStackTrace(); System.out.println("地理位置解析失敗"); } } }
步驟二:實(shí)現(xiàn)位置轉(zhuǎn)換功能
getLocationFromCoordinates
方法中使用了高德地圖的逆地理編碼API。該方法通過構(gòu)建帶有API密鑰和位置參數(shù)的URL,向高德服務(wù)器發(fā)起HTTP GET請求。接收到的響應(yīng)是JSON格式的數(shù)據(jù),我們使用Gson庫來解析這些數(shù)據(jù)以提取省市區(qū)信息。
import com.google.gson.Gson; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public static String getLocationFromCoordinates(String longitude, String latitude, String apiKey) { String url = "https://restapi.amap.com/v3/geocode/regeo?key=" + apiKey + "&location=" + longitude + "," + latitude; HttpURLConnection connection = null; BufferedReader reader = null; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } Gson gson = new Gson(); GaoDeDTO gaoDeDTO = gson.fromJson(response.toString(), GaoDeDTO.class); GaoDeDTO.RegeocodeDTO.AddressComponentDTO addressComponent = gaoDeDTO.getRegeocode().getAddressComponent(); String province = addressComponent.getProvince(); String cityStr = getStringFromObject(addressComponent.getCity()); String districtStr = getStringFromObject(addressComponent.getDistrict()); return province + cityStr + districtStr; } catch (Exception e) { return "境外地址,無法解析"; } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } } // 從對(duì)象中獲取字符串 private static String getStringFromObject(Object obj) { if (obj instanceof String) { return " " + (String) obj; } else if (obj instanceof List) { List<String> list = (List<String>) obj; if (!list.isEmpty()) { return " " + list.get(0); } } return ""; }
/** * @author lxy * @date 2024/5/13 */ @NoArgsConstructor @Data public class GaoDeDTO { @JsonProperty("info") private String info; @JsonProperty("infocode") private String infocode; @JsonProperty("regeocode") private RegeocodeDTO regeocode; @JsonProperty("status") private String status; @NoArgsConstructor @Data public static class RegeocodeDTO { @JsonProperty("addressComponent") private AddressComponentDTO addressComponent; @JsonProperty("formatted_address") private String formattedAddress; @NoArgsConstructor @Data public static class AddressComponentDTO { @JsonProperty("adcode") private String adcode; @JsonProperty("city") private Object city; @JsonProperty("citycode") private String citycode; @JsonProperty("country") private String country; @JsonProperty("district") private Object district; @JsonProperty("province") private String province; @JsonProperty("towncode") private String towncode; @JsonProperty("township") private String township; } } }
步驟三:異常處理
我們通過異常處理來確保程序的健壯性,捕獲并處理可能出現(xiàn)的異常。在網(wǎng)絡(luò)請求或JSON解析出現(xiàn)問題時(shí),程序會(huì)輸出“境外地址,無法解析”。
主要的代碼調(diào)整和優(yōu)化
- 代碼重構(gòu):將API密鑰作為方法參數(shù)傳入,增加了代碼的靈活性。
- 使用Gson進(jìn)行JSON解析:替換原有的手動(dòng)解析方法,使用Gson庫自動(dòng)映射JSON到Java對(duì)象,簡化了代碼并提高了可維護(hù)性。
- 增強(qiáng)異常處理:對(duì)網(wǎng)絡(luò)請求和JSON解析的異常處理進(jìn)行了增強(qiáng),確保程序在出錯(cuò)時(shí)可以正確關(guān)閉資源并給出清晰的錯(cuò)誤信息。
測試運(yùn)行
運(yùn)行main
方法,輸出應(yīng)顯示指定坐標(biāo)的省市區(qū)信息,例如:“河北省保定市清苑區(qū)”。
結(jié)語
通過以上步驟,你可以輕松地在任何Java應(yīng)用中實(shí)現(xiàn)經(jīng)緯度到地理位置的轉(zhuǎn)換。這對(duì)于開發(fā)地理信息系統(tǒng)(GIS)、位置服務(wù)或任何需要地理編碼的應(yīng)用都非常有用。希望這篇教程能幫助你在項(xiàng)目中實(shí)現(xiàn)位置轉(zhuǎn)換功能。
附:java利用高德地圖解析經(jīng)緯度字符串所在的城市
public class LocationUtil { /** * 通過地址位置信息,解析城市信息 * @param location 地理信息,格式 經(jīng)度,緯度 * 114.05,22.55 * @return */ public static String parseLocation(String location){ // https://lbs.amap.com/api/webservice/guide/api/georegeo 逆地址解析 // amap_api 注冊高德地圖開發(fā)者,創(chuàng)建應(yīng)用,獲取apikey //測試key:8f21643950153e066e4bfefc3d244e19 String amap_api_key = "這里需要填寫高德地圖apiKey"; String url = "https://restapi.amap.com/v3/geocode/regeo?key="+amap_api_key+"&"+"location="+location; String jsonData = HttpUtil.httpGet(url); JSONObject jsonLocation = JSON.parseObject(jsonData); String city = ""; if("1".equals(jsonLocation.getString("status"))){ JSONObject addressComponent =jsonLocation.getJSONObject("regeocode").getJSONObject("addressComponent"); Object obj = null; // 如果是非直轄市,city返回?cái)?shù)據(jù) if((obj = addressComponent.get("city")) instanceof String){ city= (String)obj; }else if ((obj = addressComponent.get("province")) instanceof String){ // 如果是直轄市,通過province返回?cái)?shù)據(jù) city= (String)obj; } city = city.replace("市",""); } return city; } }
到此這篇關(guān)于使用Java和高德地圖API將經(jīng)緯度轉(zhuǎn)換為地理位置信息的文章就介紹到這了,更多相關(guān)Java經(jīng)緯度轉(zhuǎn)換為地理位置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java Scanner輸入兩個(gè)數(shù)組的方法
今天小編就為大家分享一篇Java Scanner輸入兩個(gè)數(shù)組的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-07-07Java中IO流的BufferedOutputStream和FileOutputStream對(duì)比
這篇文章主要介紹了Java中IO流的BufferedOutputStream和FileOutputStream對(duì)比,不帶緩沖的操作,每讀一個(gè)字節(jié)就要寫入一個(gè)字節(jié),由于涉及磁盤的IO操作相比內(nèi)存的操作要慢很多,所以在讀寫的字節(jié)比較少的情況下,效率比較低,需要的朋友可以參考下2023-07-07springboot集成elasticsearch7的圖文方法
本文記錄springboot集成elasticsearch7的方法,本文通過圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-05-05Java+ElasticSearch+Pytorch實(shí)現(xiàn)以圖搜圖功能
這篇文章主要為大家詳細(xì)介紹了Java如何利用ElasticSearch和Pytorch實(shí)現(xiàn)以圖搜圖功能,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解一下2023-06-06Java 發(fā)送http請求(get、post)的示例
這篇文章主要介紹了Java 發(fā)送http請求的示例,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-10-10SpringBoot自帶模板引擎Thymeleaf使用示例詳解
Thymeleaf是一款用于渲染XML/HTML5內(nèi)容的模板引擎,類似JSP,它可以輕易的與SpringMVC等Web框架進(jìn)行集成作為Web應(yīng)用的模板引擎,本文給大家介紹SpringBoot自帶模板引擎Thymeleaf使用示例,感興趣的朋友一起看看吧2023-12-12詳解Java獲取環(huán)境變量及系統(tǒng)屬性的方法
這篇文章主要介紹了詳解Java獲取環(huán)境變量及系統(tǒng)屬性的方法,講解了System.getEnv()和System.getProperties()這兩個(gè)核心方法的使用,需要的朋友可以參考下2016-05-05基于mybatis中<include>標(biāo)簽的作用說明
這篇文章主要介紹了基于mybatis中<include>標(biāo)簽的作用說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-02-02