[筆記]C# Call Google Maps API取得資料

有時候call Google Maps API不一定會用Java Script,很多時候還是要在.CS檔案中呼叫

大多數要用住址取經緯度,或者用經緯度取得住址,再不然就是計算二點距離

 

今天上網股溝一下,將神人們的教學參拜過後,整理成自己能用的Class,老人家當然要筆記一下

至於算距離,之前就參拜過神人程式,用法也簡單,這樣得出來的距離單位是公尺

不多說,快筆記,GoogleMapServices是用來和Google Map Api溝通的class,用的時候只要傳經緯度取得住址,或傳入住址取得經緯度,用法如下

string strResult = "";
GoogleMapServices _services = new GoogleMapServices();
location _mapLocation = _services.GetLatLngByAddr("傳入住址");

strResult = "緯度" + _mapLocation.lat + ",經度" + _mapLocation.lng;  //取得經緯度

strResult = strResult+ "\n\r地址:"+_services.GetAddressByLatLng("緯度", "經度"); //傳入經緯度,取得住址

//計算距離
MapDistanceServices _distanceServices = new MapDistanceServices();
double dbdistince=_distanceServices.GetDistance(緯度1,經度1, 緯度2, 經度2);
    public class GoogleMapServices
    {
        string MapUrl = "http://maps.google.com/maps/api/geocode/json?region=tw&language=zh-TW&sensor=false";


        /// <summary>
        /// 傳入經緯度,取得住址
        /// </summary>
        /// <param name="Lat">緯度</param>
        /// <param name="Lng">經度</param>
        /// <returns>住址</returns>
        public string GetAddressByLatLng(string Lat, string Lng)
        {
            string strResult = "";
            GoogleGeoCodeResponse _mapdata =ConvertLatLngToAddress(Lat, Lng);
            if (_mapdata.status == "OK")
            {
                try
                {
                    strResult = _mapdata.results[0].formatted_address;
                }
                catch
                {

                }
            }
            return strResult;
        }
        /// <summary>
        /// 以住址查詢,回傳經緯度
        /// </summary>
        /// <param name="addr"></param>
        /// <returns></returns>
        public location GetLatLngByAddr(string addr)
        {
            location _result = new location();
            GoogleGeoCodeResponse _mapdata = new GoogleGeoCodeResponse();
            _mapdata = ConvertAddressToLatLng(addr);
            if (_mapdata.status == "OK")
            {
                try
                {
                    _result.lat = _mapdata.results[0].geometry.location.lat;
                    _result.lng = _mapdata.results[0].geometry.location.lng;
                }
                catch
                {

                }
            }
            return _result;
        }
        /// <summary>
        /// 以經緯度呼叫Google Maps Api,回傳JsonResult 
        /// </summary>
        /// <param name="Lat">緯度</param>
        /// <param name="Lng">經度</param>
        /// <returns>經緯度</returns>
        public GoogleGeoCodeResponse ConvertLatLngToAddress(string  Lat, string Lng)
        {
            string result = string.Empty;

            //string googlemapkey = "AIzaSyBGLwRnlbH6f3NYeXJFlxPT-FUdrHpv_O4";
            string url = MapUrl + "&latlng={0},{1}";
            url = string.Format(url, Lat,Lng);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            using (var response = request.GetResponse())
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {

                result = sr.ReadToEnd();
            }
            return JsonConvert.DeserializeObject<GoogleGeoCodeResponse>(result);
        }

        /// <summary>
        /// 以住址去取得Google Maps API Json results
        /// </summary>
        /// <param name="addr"></param>
        /// <returns></returns>
        public GoogleGeoCodeResponse ConvertAddressToLatLng(string addr)
        {
            string result = string.Empty;
            
            //string googlemapkey = "AIzaSyBGLwRnlbH6f3NYeXJFlxPT-FUdrHpv_O4";
            string url = MapUrl + "&address={0}";
            url   = string.Format(url, addr);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            using (var response = request.GetResponse())
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {

                result = sr.ReadToEnd();
            }

            return JsonConvert.DeserializeObject<GoogleGeoCodeResponse>(result);
        }
        public class GoogleGeoCodeResponse
        {

            public string status { get; set; }
            public results[] results { get; set; }
        }
        public class results
        {
            public string formatted_address { get; set; }
            public geometry geometry { get; set; }
            public string[] types { get; set; }
            public address_component[] address_components { get; set; }
        }

        public class geometry
        {
            public string location_type { get; set; }
            public location location { get; set; }
        }

        public class location
        {
            public string lat { get; set; }
            public string lng { get; set; }
        }

        public class address_component
        {
            public string long_name { get; set; }
            public string short_name { get; set; }
            public string[] types { get; set; }
        }
    }

 

   public class MapDistanceServices
    {
        public MapDistanceServices()
        {
        }
        private const double EARTH_RADIUS = 6378.137;
        private double rad(double d)
        {
            return d * Math.PI / 180.0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="lat1">緯度1</param>
        /// <param name="lng1">經度1</param>
        /// <param name="lat2">緯度2</param>
        /// <param name="lng2">經度2</param>
        /// <returns></returns>
        public double GetDistance(double lat1, double lng1, double lat2, double lng2)
        {
            double dblResult = 0;
            double radLat1 = rad(lat1);
            double radLat2 = rad(lat2);
            double distLat = radLat1 - radLat2;
            double distLng = rad(lng1) - rad(lng2);
            dblResult = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(distLat / 2), 2) +
                            Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(distLng / 2), 2)));
            dblResult = dblResult * EARTH_RADIUS;
            //dblResult = Math.Round(dblResult * 10000) /10000;  //這回傳變成公里,少3個0變公尺
            dblResult = Math.Round(dblResult * 10000) / 10;

            return dblResult;
        }
    }

 

打雜打久了,就變成打雜妹

程式寫久了,就變成老乞丐