前面我們已經實現了坐標定位及前端顯示,而坐標的獲取一般只在移動設備上,對於PC端難以得到。但是在PC端,我們可以得到相應的IP。在得到了IP之後,我們就可以進行定們了。代碼如下:
public class BaiduMap
{
///
/// 依據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;
///
/// 依據IP獲取定位信息
///
///坐標
///
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(responseText);
}
catch (Exception)
{
return null;
}
return locationResult;
}
#endregion
}
注;
(1).使用const定義Api的URL模板。
(2).百度KEY自行申請後填入。
(3).IpLOcationResult接收json數據的反序列化結果,該類的實現如下
namespace MapApi.Baidu
{
[Serializable]
public class IpLocationResult
{
///
/// 狀態
///
public String status { get; set; }
///
/// 地址
///
public String address { get; set; }
///
/// 內容
///
public IpLocationResult_Content content { get; set; }
}
#region IpLocationResult_Content
///
/// 定位結果文本
///
[Serializable]
public class IpLocationResult_Content
{
///
/// 地址
///
public String address { get; set; }
///
/// 地址明細
///
public IpLocationResult_Content_AddressDetail address_detail { get; set; }
///
/// 經緯度
///
public Coordinate point { get; set; }
}
///
/// 定位結果文本之地址明細
///
[Serializable]
public class IpLocationResult_Content_AddressDetail
{
///
/// 城市
///
public String city { get; set; }
///
/// 城市代碼
///
public String 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; }
}
#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記錄》。