C#调用Geocoding API进行地理编码与逆编码
使用C#调用Geocoding API来将地址转为经纬度,或者将经纬度转变为具体的地址。
Geocoding API的详细介绍参见:http://developer.baidu.com/map/webservice-geocoding.htm
地理编码示例:
网页调用:
C#代码实现:
1 /// <summary> 2 /// 地址编码 3 /// </summary> 4 /// <param name="ak">百度密钥</param> 5 /// <param name="address">详细地址</param> 6 /// <param name="city">城市</param> 7 /// <returns></returns> 8 public string GeoEncoding(string ak, string address,string city) 9 { 10 string json = ","; 11 try 12 { 13 WebClient client = new WebClient(); 14 client.Encoding = UTF8Encoding.UTF8; 15 string url = String.Format("http://api.map.baidu.com/geocoder/v2/?ak={0}&address={1}&city={2}&output=json", ak, address, city); 16 17 //将返回的json数据转为JSON对象 18 JObject jo = ((JObject)JsonConvert.DeserializeObject(client.DownloadString(url))); 19 string status = jo["status"].ToString(); 20 if (status == "0") 21 { 22 //正常返回 23 json = jo["result"]["location"]["lat"].ToString() + "," + jo["result"]["location"]["lng"].ToString(); 24 } 25 } 26 catch(Exception ex) 27 { 28 //异常处理 29 } 30 return json; 31 }
逆地址编码示例:
网页调用:
C#代码实现:
1 /// <summary> 2 /// 逆地址编码 3 /// </summary> 4 /// <param name="ak">百度密钥</param> 5 /// <param name="longitude">经度</param> 6 /// <param name="latitude">纬度</param> 7 /// <returns></returns> 8 public string GeoDecoding(string ak, string longitude, string latitude) 9 { 10 string json = ""; 11 try 12 { 13 WebClient client = new WebClient(); 14 client.Encoding = UTF8Encoding.UTF8; 15 string url = String.Format("http://api.map.baidu.com/geocoder/v2/?ak={0}&location={1},{2}&output=json", ak, longitude, latitude); 16 17 //将返回的json数据转为JSON对象 18 JObject jo = ((JObject)JsonConvert.DeserializeObject(client.DownloadString(url))); 19 string status = jo["status"].ToString(); 20 if (status == "0") 21 { 22 //正常返回 23 json = jo["result"]["formatted_address"].ToString() ; 24 } 25 } 26 catch (Exception ex) 27 { 28 //异常处理 29 } 30 return json; 31 }
posted on 2013-12-24 14:33 nxgliming 阅读(1257) 评论(0) 编辑 收藏 举报