首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

使用百度地圖 GeoCoding API 將地址轉換為經緯度

     編輯:Java 相關知識

場景介紹

許多應用需要根據用戶輸入的地址(如路名、地標、商場名)獲取對應的經緯度。由於數據庫難以涵蓋所有可能的地址,調用地圖服務商提供的地理編碼 API 是常用解決方案。本文演示如何使用百度地圖 GeoCoding API 實現地址到經緯度的轉換。

核心實現

1. 構建請求 URL

public String geoCodeRequestUrl(String query) throws UnsupportedEncodingException {
    String url = WeChatConstant.BASEURL + "geocoder?address=" 
                 + URLEncoder.encode(query, "UTF-8") 
                 + "&key=" + WeChatConstant.MAPKEY 
                 + "&output=" + WeChatConstant.OUTPUTFORMAT;
    return url;
}

參數說明:address 為編碼後的查詢地址,key 為百度開發者密鑰,output 指定返回格式(XML 或 JSON)。

2. 發送 HTTP GET 請求並獲取響應

public String getGeoCode(String query) throws ClientProtocolException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    String url = geoCodeRequestUrl(query);
    HttpGet httpget = new HttpGet(url);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpClient.execute(httpget, responseHandler);
    return responseBody; // 百度返回的 XML 格式經緯度信息
}

單元測試與結果解析

@Test
public void testGeoCode() throws Exception {
    BaiduMapService bms = new BaiduMapService();
    String response = bms.getGeoCode("上地十街十號");
    BaiduGeoCodeResponse res = BaiduGeoCodeResponse.getBaiduGeoCode(response); // 解析 XML
    System.out.println(res.toString());
}

輸出結果示例

<GeocoderSearchResponse>
  <status>OK</status>
  <result>
    <location>
      <lat>40.057098</lat>
      <lng>116.307175</lng>
    </location>
    <precise>1</precise>
    <confidence>80</confidence>
    <level>道路</level>
  </result>
</GeocoderSearchResponse>

BaiduGeoCodeResponse [lat=40.057098, lng=116.307175]

注意事項

  • 需先在百度開放平台註冊應用獲取 AK(MAPKEY)。
  • 請求頻率受限,高並發場景需做緩存或排隊處理。
  • 返回的 precise=1 表示精確匹配,confidence 為置信度,level 為地址層級。
  • 生產環境建議使用 HTTPS 並妥善保管 AK。

出處:https://www.qiyadeng.com/

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved