C#根据经纬度获取物理地址

2021-04-27 19:29

阅读:605

标签:array   des   count   location   根据   response   request   text   mat   

调用命名空间:

using System.Net;
using System.IO;
using System.Xml;

 

调用事例:

private string GetAddress(string lng, string lat) 

{

      try

            {

                string url = @"http://api.map.baidu.com/geocoder/v2/?ak=oGdNg8wTEMEIsC0uzqqD3nq0&callback=renderReverse&location=" + lat + "," + lng + @"&output=xml&pois=1";

                WebRequest request = WebRequest.Create(url);

                request.Method = "POST";

                XmlDocument xmlDoc = new XmlDocument();

                string sendData = xmlDoc.InnerXml;

                byte[] byteArray = Encoding.Default.GetBytes(sendData);

                Stream dataStream = request.GetRequestStream();

                dataStream.Write(byteArray, 0, byteArray.Length);

                dataStream.Close();

                WebResponse response = request.GetResponse();

                dataStream = response.GetResponseStream();

                StreamReader reader = new StreamReader(dataStream, System.Text.Encoding.GetEncoding("utf-8"));

                string responseXml = reader.ReadToEnd();

                XmlDocument xml = new XmlDocument();

                xml.LoadXml(responseXml);

                string status = xml.DocumentElement.SelectSingleNode("status").InnerText;                                         if (status == "0")

                {

                    XmlNodeList nodes = xml.DocumentElement.GetElementsByTagName("formatted_address");

                    if (nodes.Count > 0)

                    {

                        return nodes[0].InnerText;

                    }

                    else

                         return "未获取到位置信息,错误码3";

                    }

                else

                {

                    return "未获取到位置信息,错误码1";

                }

            }

            catch (System.Exception ex)

            {

                return "未获取到位置信息,错误码" + ex + "";

            }

 }

 

---注意:

    当status=“0”但nodes[0].InnerText结果依然为null时,在网址上查看url是否可以得到数据。

C#根据经纬度获取物理地址

标签:array   des   count   location   根据   response   request   text   mat   

原文地址:http://www.cnblogs.com/bingsying/p/7846724.html

上一篇:C# 位运算

下一篇:学习Java推荐的书籍


评论


亲,登录后才可以留言!