C#通过地址获取省市区(基于百度地图API)
最近公司有个需求,想通过地址获取对应的省市区,本来想直接通过对地址的截取,对于完整的地址还可以,不完整的就没法用了
所以本篇通过百度地图API来获取地址
第一步:申请ak密钥
登录百度地图开放平台,按照提示一步步申请即可,效果如下
第二步:根据地理编码API获取地址对应的经纬度
ak为密钥,123456是随便填的,填上你自己的ak即可
string ak="123456"; string Url = @"http://api.map.baidu.com/geocoding/v3/?address="+txtAddress.Text.Trim()+"&output=json&ak=" + ak; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.KeepAlive = false; request.Method = "GET"; request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); response.Close(); request.Abort(); txtLocation.Text = retString; JObject obj_RawData = (JObject)(JsonConvert.DeserializeObject(retString)); JObject obj_Result = (JObject)(JsonConvert.DeserializeObject(obj_RawData["result"].ToString())); JObject obj_Loaction = (JObject)(JsonConvert.DeserializeObject(obj_Result["location"].ToString())); string lng = obj_Loaction["lng"].ToString(); //经度值 string lat = obj_Loaction["lat"].ToString(); //纬度值
第三步:在根据逆地理编码API获取经纬度对应的省市区
1 Url = @"http://api.map.baidu.com/reverse_geocoding/v3/?ak=" + ak + "&output=json&coordtype=bd09ll&location=" + lat + "," + lng; 2 3 request = (HttpWebRequest)WebRequest.Create(Url); 4 request.KeepAlive = false; 5 request.Method = "GET"; 6 request.ContentType = "application/json"; 7 8 response = (HttpWebResponse)request.GetResponse(); 9 myResponseStream = response.GetResponseStream(); 10 myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); 11 retString = myStreamReader.ReadToEnd(); 12 myStreamReader.Close(); 13 myResponseStream.Close(); 14 response.Close(); 15 request.Abort();
以上代码可获取对应的省市区,返回的json例子如下:
"addressComponent": {
"country": "中国",
"country_code": 0,
"country_code_iso": "CHN",
"country_code_iso2": "CN",
"province": "浙江省",
"city": "嘉兴市",
"city_level": 2,
"district": "平湖市",
"town": "",
"adcode": "330482",
"street": "兴平一路",
"street_number": "",
"direction": "附近",
"distance": "2"
}