C#微信開發之旅(七):根據經緯度獲取地址(百度地圖Api)


開發過程中遇到這樣的需求,根據用戶的地理位置不同,顯示不同區域的產品。

這里用到了微信:獲取用戶地理位置 的功能,(每隔5秒上報 或 進入回話時上報一次),我們根據微信推送過來的經緯度,來轉換成實際地址,這里用到的是百度地圖Api(要用的話先申請百度ak)。

PS:微信的這個功能很不穩定,靠它不靠譜,經常不推送。。。(后來加了手動定位,百度地圖Web定位組件 還不錯,不是廣告!0.0)

        #region 根據經緯度 獲取地址信息 BaiduApi

        /// <summary>
        /// 根據經緯度  獲取 地址信息
        /// </summary>
        /// <param name="lat">經度</param>
        /// <param name="lng">緯度</param>
        /// <returns></returns>
        public static BaiDuGeoCoding GeoCoder(string lat, string lng)
        {
            string url = string.Format(WeiXinConst.Baidu_GeoCoding_ApiUrl, lat, lng);

            var model = HttpClientHelper.GetResponse<BaiDuGeoCoding>(url);

            return model;
        }

        #endregion

BaiduGeoCoding是針對Api相應結果封裝的對象:

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; }
    }

調用:

            //需配置 WeiXineConst的BaiduAk
            string lat = "31.1430"; //經度
            string lng = "121.2943";// 緯度
            var model = WeiXinHelper.GeoCoder(lat, lng);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM