C#的百度地圖開發(五)IP定位,
前面我們已經實現了座標定位及最上層顯示,而座標的擷取一般只在行動裝置上,對於PC端難以得到。但是在PC端,我們可以得到相應的IP。在得到了IP之後,我們就可以進行定們了。代碼如下:
public class BaiduMap { /// <summary> /// 依據IP擷取定位資訊的URL模板。 /// 參數1:百度地圖API的KEY。 /// 參數2:IP。 public const string IP_LOCATION_URL_TEMPLATE = "http://api.map.baidu.com/location/ip?ak={0}&ip={1}&coor=bd09ll"; /// <summary> /// 依據IP擷取定位資訊 /// </summary> /// <param name="coordinate">座標</param> /// <returns></returns> public static IpLocationResult FetchLocation(String ip) { if (String.IsNullOrWhiteSpace(ip)) { return null; } String ipLocationUrl = String.Format(IP_LOCATION_URL_TEMPLATE, MAP_KEY_BAI_DU, ip); String responseText = RequestHelper.RequestUrl(ipLocationUrl, null); if (String.IsNullOrWhiteSpace(responseText)) { return null; } IpLocationResult locationResult = null; try { locationResult = Newtonsoft.Json.JsonConvert.DeserializeObject<IpLocationResult>(responseText); } catch (Exception) { return null; } return locationResult; } #endregion}注;
(1).使用const定義Api的URL模板。
(2).百度KEY自行申請後填入。
(3).IpLOcationResult接收json資料的還原序列化結果,該類的實現如下
namespace MapApi.Baidu{ [Serializable] public class IpLocationResult { /// <summary> /// 狀態 /// </summary> public String status { get; set; } /// <summary> /// 地址 /// </summary> public String address { get; set; } /// <summary> /// 內容 /// </summary> public IpLocationResult_Content content { get; set; } } #region IpLocationResult_Content /// <summary> /// 定位結果文本 /// </summary> [Serializable] public class IpLocationResult_Content { /// <summary> /// 地址 /// </summary> public String address { get; set; } /// <summary> /// 地址明細 /// </summary> public IpLocationResult_Content_AddressDetail address_detail { get; set; } /// <summary> /// 經緯度 /// </summary> public Coordinate point { get; set; } } /// <summary> /// 定位結果文本之地址明細 /// </summary> [Serializable] public class IpLocationResult_Content_AddressDetail { /// <summary> /// 城市 /// </summary> public String city { get; set; } /// <summary> /// 城市代碼 /// </summary> public String city_code { get; set; } /// <summary> /// 地區 /// </summary> public String district { get; set; } /// <summary> /// 省份 /// </summary> public String province { get; set; } /// <summary> /// 街道 /// </summary> public String street { get; set; } /// <summary> /// 門牌號 /// </summary> public String street_number { get; set; } } #endregion}
測試代碼如下:
protected void btnTest_Click(object sender, EventArgs e) { String ip = "47.153.128.1"; IpLocationResult ipLocationResult = BaiduMap.FetchLocation(ip); Alert.Show(ipLocationResult.status.ToString()); }
測試結果如;
注:
(1).可以看到依據IP已經得到了定位的結果。不過IP定位的結果精度只能到城市,所以是一個精略的定位結果,如果需要精確定位,還是要使用經緯度座標。
(2).從結果中可以看到該IP對應的經緯度,所以可以通過這個經緯度在前端的地圖上顯示定位(具體的可以參照前面的文章)。
那對於網站,要如何去得到這些IP的值呢?請參看後文《C#的百度地圖開發(六)使用者訪問網頁的IP記錄》。
轉載請註明出處。