許多應用需要根據用戶輸入的地址(如路名、地標、商場名)獲取對應的經緯度。由於數據庫難以涵蓋所有可能的地址,調用地圖服務商提供的地理編碼 API 是常用解決方案。本文演示如何使用百度地圖 GeoCoding API 實現地址到經緯度的轉換。
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)。
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]
precise=1 表示精確匹配,confidence 為置信度,level 為地址層級。