現(xiàn)在經(jīng)常需要根據(jù)用戶提供的位置,提供一些和位置相關(guān)的信息。有時(shí)可以直接確定用戶的經(jīng)度和緯度,有時(shí)不一定可以確定用戶的經(jīng)度和緯度信息,用戶是 通過輸入一些路名、標(biāo)志性建筑或是商場名等位置,但是我們的數(shù)據(jù)庫可能并沒有存法用戶可能輸入的這些位置信息的經(jīng)度緯度,這時(shí)候可以使用一些地圖提供的 API來確定,用戶所輸入的位置信息的經(jīng)度和緯度。
我們使用百度地圖提供的GeoCoding API實(shí)現(xiàn)從位置信息到經(jīng)度緯度的轉(zhuǎn)換,詳細(xì)的使用說明可以參考GeoCoding API。我們這里做一個(gè)簡單的演示 public String getGeoCode(String query) throws ClientProtocolException, IOException{
HttpClient httpClient = new DefaultHttpClient();
String url = geoCodeRequestUrl(query);
logger.log(Level.INFO, url);
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpget, responseHandler);//百度返回的經(jīng)度緯度信息xml
logger.log(Level.INFO,"baidu response:"+responseBody);
return responseBody;
}
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;
}
HttpClient httpClient = new DefaultHttpClient();
String url = geoCodeRequestUrl(query);
logger.log(Level.INFO, url);
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpget, responseHandler);//百度返回的經(jīng)度緯度信息xml
logger.log(Level.INFO,"baidu response:"+responseBody);
return responseBody;
}
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;
}
使用JUnit進(jìn)行測試
@Test
public void testGeoCode() throws Exception {
BaiduMapService bms = new BaiduMapService();
String response = bms.getGeoCode("上地十街十號(hào)");
BaiduGeoCodeResponse res = BaiduGeoCodeResponse.getBaiduGeoCode(response);//解析xml
System.out.println(res.toString());
}
public void testGeoCode() throws Exception {
BaiduMapService bms = new BaiduMapService();
String response = bms.getGeoCode("上地十街十號(hào)");
BaiduGeoCodeResponse res = BaiduGeoCodeResponse.getBaiduGeoCode(response);//解析xml
System.out.println(res.toString());
}
輸出的結(jié)果
<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]
<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]
原創(chuàng)文章,轉(zhuǎn)載請(qǐng)注明: 轉(zhuǎn)載自http://www.qiyadeng.com/
本文鏈接地址: 確定路名、標(biāo)志性建筑和商場名的經(jīng)度緯度