使用百度地图GeoCoding API确定路名、标志性建筑和商场名的经度纬度2013-07-17 qiyadeng 现在经常需要根据用户提供的位置,提供一些和位置相关的信息。有时可以直接确定用户的经度和纬度,有时不一定可以确定用户的经度和纬度信息,用户是 通过输入一些路名、标志性建筑或是商场名等位置,但是我们的数据库可能并没有存法用户可能输入的这些位置信息的经度纬度,这时候可以使用一些地图提供的 API来确定,用户所输入的位置信息的经度和纬度。我们使用百度地图提供的GeoCoding API实现从位置信息到经度纬度的转换,详细的使用说明可以参考GeoCoding API。我们这里做一个简单的演示
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);//百度返回的经度纬度信息xmllogger.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进行测试
@Testpublic void testGeoCode() throws Exception {BaiduMapService bms = new BaiduMapService();String response = bms.getGeoCode("上地十街十号");BaiduGeoCodeResponse res = BaiduGeoCodeResponse.getBaiduGeoCode(response);//解析xmlSystem.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]
出处:http://www.qiyadeng.com/