直接上代码:解释都在代码中
ak 要自己去百度地图申请.
其中申请ak的时候,有个属性render直接填*就行.
namespace HampWebControl 是我的空间命名!
namespace HampWebControl 是我的空间命名!
namespace HampWebControl 是我的空间命名!
using Newtonsoft.Json; using System; using System.IO; using System.Net; using System.Security.Policy; using System.Text; namespace HampWebControl { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { var a = ReturnXY(); #region 这里弹出窗口来查看xy的值,实际业务中应该是要保存这个xy的值的 string X = a.x.ToString(); string Y = a.y.ToString(); string alert = "x值:"+X+",y值: "+Y; Response.Write("<script>alert(‘"+ alert + "‘);</script>"); #endregion } public static Point ReturnXY() { string strBuff = ""; Url url = new Url("http://api.map.baidu.com/location/ip?ak=" + "自己申请的百度AK" + "&coor=bd09ll"); ///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,,需通过WebRequest的Creat方法 建立,并进行强制的类型转换 HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url.Value); ///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换 HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse(); ///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容 ///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理 Stream respStream = httpResp.GetResponseStream(); ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以 ///StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8) StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8); strBuff = respStreamReader.ReadToEnd(); Models models = JsonConvert.DeserializeObject<Models>(strBuff); var xy=models.content.point; return xy; } } public class Models{ public string address { get; set; } public Content content { get; set; } public int status { get; set; } } public class Content { public string address { get; set; } public AddressDetail address_detail { get; set; } public Point point { get; set; } } public class AddressDetail { public string city { get; set; } public int city_code { get; set; } public string district { get; set; } public string province { get; set; } public string street { get; set; } public string street_number { get; set; } } public class Point { public Decimal x { get; set; } public Decimal y { get; set; } } }