C#通过地址获取省市区(基于百度地图API)

最近公司有个需求,想通过地址获取对应的省市区,本来想直接通过对地址的截取,对于完整的地址还可以,不完整的就没法用了

所以本篇通过百度地图API来获取地址

第一步:根据地址获取对应的经纬度

ak为密钥,申请百度开发账号可获取,通过 geocoding 获取到经纬度

            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(); //纬度值

 

第二步:在根据经纬度获取对应的省市区

 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"
}

猜你喜欢

转载自www.cnblogs.com/kenjiang/p/11363793.html
0条评论
添加一条新回复