C#百度api 根据经纬度获取地址

 1  public string GetAddress(string lat, string lng)
 2         {
 3             try
 4             {
 5                 string res = "";
 6 
 7                 string url = @"http://api.map.baidu.com/geocoder/v2/?ak=ZndyfXErtTiZQwfgNgQ7yqb7ALKdk4DA&location=" + lat + "," + lng + "&output=xml";
 8                 WebRequest request = WebRequest.Create(url);
 9                 request.Method = "POST";
10                 XmlDocument xmlDoc = new XmlDocument();
11                 string sendData = xmlDoc.InnerXml;
12                 byte[] byteArray = Encoding.Default.GetBytes(sendData);
13 
14                 Stream dataStream = request.GetRequestStream();
15                 dataStream.Write(byteArray, 0, byteArray.Length);
16                 dataStream.Close();
17 
18                 WebResponse response = request.GetResponse();
19                 dataStream = response.GetResponseStream();
20                 StreamReader reader = new StreamReader(dataStream, System.Text.Encoding.GetEncoding("utf-8"));
21                 string responseXml = reader.ReadToEnd();
22 
23                 XmlDocument xml = new XmlDocument();
24                 xml.LoadXml(responseXml);
25                 string status = xml.DocumentElement.SelectSingleNode("status").InnerText;
26                 if (status == "0")
27                 {
28 
29                     XmlNodeList nodes = xml.DocumentElement.GetElementsByTagName("formatted_address");
30                     XmlNodeList nodes1 = xml.DocumentElement.GetElementsByTagName("sematic_description");
31                     if (nodes.Count > 0 && !string.IsNullOrEmpty(nodes[0].InnerText))
32                     {
33                         res += "地址信息: " + nodes[0].InnerText;
34                     }
35                     if (nodes1.Count > 0 && !string.IsNullOrEmpty(nodes1[0].InnerText))
36                     {
37                         res += "  结果描述: " + nodes1[0].InnerText;
38                     }
39                     if (nodes.Count <= 0 && nodes1.Count <= 0)
40                         res = "未获取到位置信息,错误码3";
41                 }
42                 else
43                 {
44                     res = "未获取到位置信息,错误码1";
45                 }
46                 return res;
47             }
48             catch (System.Exception ex)
49             {
50                 return "未获取到位置信息,错误码2";
51             }
52         }

测试连接

http://api.map.baidu.com/geocoder/v2/ak=ZndyfXErtTiZQwfgNgQ7yqb7ALKdk4DA&location=39.963175,116.400244&output=json

接口详细说明地址:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding

posted @ 2016-11-09 20:48  指间的徘徊  阅读(1494)  评论(0编辑  收藏  举报