在使用百度地图的 逆地理编码 功能时遇到了一些问题,官方的文档有一些问题,并且说得也不是很清楚,现在把C# 版本的引用方式和调用方法在这里记录一下,给有需要的人参考一下。
SN码生成类
public class AKSNCaculater{private static string MD5(string password){try{System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.MD5.Create();byte[] hash_out = puteHash(System.Text.Encoding.UTF8.GetBytes(password));var md5_str = BitConverter.ToString(hash_out).Replace("-", "");return md5_str.ToLower();}catch{throw;}}private static string UrlEncode(string str){str = System.Web.HttpUtility.UrlEncode(str);byte[] buf = Encoding.ASCII.GetBytes(str);//等同于Encoding.ASCII.GetBytes(str)for (int i = 0; i < buf.Length; i++)if (buf[i] == '%'){if (buf[i + 1] >= 'a') buf[i + 1] -= 32;if (buf[i + 2] >= 'a') buf[i + 2] -= 32;i += 2;}return Encoding.ASCII.GetString(buf);//同上,等同于Encoding.ASCII.GetString(buf)}private static string HttpBuildQuery(IDictionary<string, string> querystring_arrays){StringBuilder sb = new StringBuilder();foreach (var item in querystring_arrays){sb.Append(UrlEncode(item.Key));sb.Append("=");sb.Append(UrlEncode(item.Value));sb.Append("&");}sb.Remove(sb.Length - 1, 1);return sb.ToString();}public static string CaculateAKSN(string ak, string sk, string url, IDictionary<string, string> querystring_arrays){var queryString = HttpBuildQuery(querystring_arrays);var str = UrlEncode(url + "?" + queryString + sk);return MD5(str);}}
调用方法:
public class LocationService{/// <summary>/// 根据经纬度获取地理位置/// </summary>/// <param name="lat">纬度</param>/// <param name="lng">经度</param>/// <returns>具体的地埋位置</returns>public static string GetLocation(string lat, string lng){try{var ak = "你的AK";var sk = "你的SK";var uri = "http://api.";var path = "/reverse_geocoding/v3/";var param = new Dictionary<string, string>();string location = string.Format("{0},{1}", lat, lng);param.Add("ak", ak);param.Add("location", location);param.Add("output", "json");param.Add("coordtype", "wgs84ll");var sn = AKSNCaculater.CaculateAKSN(ak, sk, path, param);location = string.Format("{0}%2C{1}", lat, lng);var url = string.Format("{0}{1}?ak={2}&location={3}&output=json&coordtype=wgs84ll&sn={4}",uri,path,ak,location,sn);//发送 http get请求,可以使用自己顺手的方法var str = mon.Utils.GetHttpPage(url, 1000);return str;}catch (Exception){return "";}}}
这样就可以了,需要注意的是拼装经纬度参数这部分,传入生成SN的参数要使用逗号分隔,但在生成URL时,必须将逗号转义成 %2C,否则会提示APP SN校验失败。