C#根據經緯度獲取實體地址

林堯彬發表於2020-04-04

廢話不多說,直接上程式碼:

1.首先新建幾個類,定義一些屬性:

public class BaiDuGeoCoding
{
    public int Status { get; set; }
    public Result Result { get; set; }
}

public class Result
{
    public Location Location { get; set; }

    public string Formatted_Address { get; set; }

    public string Business { get; set; }

    public AddressComponent AddressComponent { get; set; }

    public string CityCode { get; set; }
}

public class AddressComponent
{
    /// <summary>
    /// 省份
    /// </summary>
    public string Province { get; set; }
    /// <summary>
    /// 城市名
    /// </summary>
    public string City { get; set; }

    /// <summary>
    /// 區縣名
    /// </summary>
    public string District { get; set; }

    /// <summary>
    /// 街道名
    /// </summary>
    public string Street { get; set; }

    public string Street_number { get; set; }

}

public class Location
{
    public string Lng { get; set; }
    public string Lat { get; set; }
}

2.新建一個幫助類根據URL獲取頁面內容:

public class HttpClientHelper
{
    /// <summary>
    /// GET請求
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url"></param>
    /// <returns></returns>
    public static T GetResponse<T>(string url) where T : class,new()
    {
        string returnValue = string.Empty;
        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
        webReq.Method = "GET";
        webReq.ContentType = "application/json";
        using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
        {
            using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                returnValue = streamReader.ReadToEnd();
                T result = default(T);
                result = JsonConvert.DeserializeObject<T>(returnValue);
                return result;
            }
        }
    }
}

3.定義欄位和方法獲取:

//百度地圖Api  Ak
public const string BaiduAk = "9TxmFS8X1EXcUGZkqsDM4GKuayamwkbr";

/// <summary>
/// 經緯度  逆地理編碼 Url  需要Format 0.ak  1.經度  2.緯度
/// </summary>
private const string BaiduGeoCoding_ApiUrl = "http://api.map.baidu.com/geocoder/v2/?ak={0}&location={1},{2}&output=json&pois=0";

/// <summary>
/// /// <summary>
/// 經緯度  逆地理編碼 Url  需要Format 0.經度  1.緯度 
/// </summary>
/// </summary>
public static string Baidu_GeoCoding_ApiUrl
{
    get
    {
        return string.Format(BaiduGeoCoding_ApiUrl, BaiduAk, "{0}", "{1}");
    }
}

/// <summary>
/// 根據經緯度  獲取 地址資訊
/// </summary>
/// <param name="lat">經度</param>
/// <param name="lng">緯度</param>
/// <returns></returns>
public static BaiDuGeoCoding GeoCoder(string lat, string lng)
{
    string url = string.Format(Baidu_GeoCoding_ApiUrl, lat, lng);
    var model = HttpClientHelper.GetResponse<BaiDuGeoCoding>(url);
    return model;
}

4.呼叫方法:

string lat = "22.228962"; 
string lng = "113.308784";
var model = GeoCoder(lat, lng); //model拿到的就是詳細實體地址

 

轉載於:https://www.cnblogs.com/genesis/p/6644895.html

相關文章