Пример #1
0
        // Author: Harith Neralla
        // ASU CSE 445 Summer 2017
        // 06/10/2017

        // Service obtains the weather conditions and location details using a ZIP code as parameter.
        // External services used are from the Weather Underground API.
        // External services invoked: Geo-lookup (returns location details) and Current Conditions (returns weather details).
        // This web service parses JSON responses from the API services using the JSON.NET library

        public string[] getLocationDetails(string zipcode)
        {
            List <string>     details = new List <string>();     // List of strings to return later
            ZIPRootObject     obj     = new ZIPRootObject();     // Creates object to deserialize JSON doc into
            WeatherRootObject obj1    = new WeatherRootObject(); // Creates object to deserialize JSON doc into
            string            wind;
            string            nearbyCities;
            string            url = "http://api.wunderground.com/api/a88ec4d422339198/geolookup/q/" + zipcode + ".json"; // Builds the url to load from (includes developer API key)

            using (var webClient = new System.Net.WebClient())
            {
                var json = webClient.DownloadString(url);                                  // Retrieves JSON Document

                obj = JsonConvert.DeserializeObject <ZIPRootObject>(json);                 // Deserializes the JSON document

                if (obj.response.error == null)                                            // Makes sure no error was returned
                {
                    details.Add("City: " + obj.location.city + ", " + obj.location.state); // Adds "City, State" to the list

                    // Builds the nearby cities string
                    nearbyCities = "Nearby Cities: ";
                    foreach (ZIPRootObject.Location.Nearby_Weather_Stations.Airport.Station station in obj.location.nearby_weather_stations.airport.station)
                    {
                        nearbyCities += station.city + ", ";
                    }
                    nearbyCities = nearbyCities.TrimEnd(' ').TrimEnd(','); // Removes the extra comma
                    details.Add(nearbyCities);                             // Adds the cities to the list

                    //Rebuilds URL to retrieve the weather conditions
                    url  = "http://api.wunderground.com/api/a88ec4d422339198/conditions/q/" + obj.location.state + "/" + obj.location.city + ".json";
                    json = webClient.DownloadString(url);

                    obj1 = JsonConvert.DeserializeObject <WeatherRootObject>(json); // Deserializes the JSON document
                    wind = "Wind " + obj1.current_observation.wind_string + " ";    // Builds the wind string

                    // Adds various different details to the list
                    details.Add("Elevation: " + obj1.current_observation.observation_location.elevation);
                    details.Add("Current Temperature: " + obj1.current_observation.temperature_string);
                    details.Add("Feels Like: " + obj1.current_observation.feelslike_string);
                    details.Add("Relative Humidity: " + obj1.current_observation.relative_humidity);
                    details.Add(wind);
                    details.Add(obj1.current_observation.forecast_url); // Adds URL for user to access more information
                }
                else
                {
                    details.Add(obj.response.error.description); // adds the error message into the list
                }
            }

            return(details.ToArray());
        }
        public string WeatherDetail(string City)
        {
            //Assign API KEY which received from OPENWEATHERMAP.ORG
            string appId = "d8c2be690a8086d8dd04a6cf4e6df6f5";

            //API path with CITY parameter and other parameters.
            string url = string.Format("https://api.openweathermap.org/data/2.5/weather?q={0}&units=metric&cnt=1&APPID={1}", City, appId);

            var jsonstring = "";

            using (WebClient client = new WebClient())
            {
                try
                {
                    string json = client.DownloadString(url);

                    //Converting to OBJECT from JSON string.
                    WeatherRootObject weatherInfo = (new JavaScriptSerializer()).Deserialize <WeatherRootObject>(json);

                    //Special VIEWMODEL design to send only required fields not all fields which received from
                    //www.openweathermap.org api
                    ResultViewModel rslt = new ResultViewModel();

                    rslt.Country       = weatherInfo.sys.country;
                    rslt.City          = weatherInfo.name;
                    rslt.Lat           = Convert.ToString(weatherInfo.coord.lat);
                    rslt.Lon           = Convert.ToString(weatherInfo.coord.lon);
                    rslt.Description   = weatherInfo.weather[0].description;
                    rslt.Humidity      = Convert.ToString(weatherInfo.main.humidity);
                    rslt.Temp          = Convert.ToString(weatherInfo.main.temp);
                    rslt.TempFeelsLike = Convert.ToString(weatherInfo.main.feels_like);
                    rslt.TempMax       = Convert.ToString(weatherInfo.main.temp_max);
                    rslt.TempMin       = Convert.ToString(weatherInfo.main.temp_min);
                    rslt.WeatherIcon   = weatherInfo.weather[0].icon;

                    //Converting OBJECT to JSON String
                    jsonstring = new JavaScriptSerializer().Serialize(rslt);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.InnerException);
                }

                //Return JSON string.
                return(jsonstring);
            }
        }
Пример #3
0
        private async void GetWeather()
        {
            ColorSnow.Color = Color.FromArgb(255, 255, 255, 255);
            ColorRain.Color = Color.FromArgb(255, 16, 155, 251);

            Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.f") + " - Request Weather Data...");
            WebRequest W_wrGETURL = WebRequest.Create("http://api.wunderground.com/api/877361112ea5ac9f/geolookup/conditions/hourly/q/Switzerland/Winterthur.json");

            WebResponse W_response = await W_wrGETURL.GetResponseAsync();

            Stream       W_dataStream = W_response.GetResponseStream();
            StreamReader W_reader     = new StreamReader(W_dataStream);
            string       W_sResponse  = W_reader.ReadToEnd();

            Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.f") + " - ...Data received");
            Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.f") + " - Loading Weather Data Stream");
            WeatherRootObject WeatherObj = JsonConvert.DeserializeObject <WeatherRootObject>(W_sResponse);

            Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.f") + " - Parsing Weather Data Stream");

            Double[] temp_raw = new Double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            Double[] rain_raw = new Double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            Double   vAvg, vScale;

            Label_Time1.Text = WeatherObj.hourly_forecast[3].FCTTIME.hour_padded + ":00";
            Label_Time2.Text = WeatherObj.hourly_forecast[6].FCTTIME.hour_padded + ":00";
            Label_Time3.Text = WeatherObj.hourly_forecast[9].FCTTIME.hour_padded + ":00";
            Label_Time4.Text = WeatherObj.hourly_forecast[12].FCTTIME.hour_padded + ":00";
            Label_Time5.Text = WeatherObj.hourly_forecast[15].FCTTIME.hour_padded + ":00";
            Label_Time6.Text = WeatherObj.hourly_forecast[18].FCTTIME.hour_padded + ":00";

            Label_Temp1.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[3].temp.metric);
            Label_Temp2.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[6].temp.metric);
            Label_Temp3.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[9].temp.metric);
            Label_Temp4.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[12].temp.metric);
            Label_Temp5.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[15].temp.metric);
            Label_Temp6.Text = String.Format("{0:N0}°C", WeatherObj.hourly_forecast[18].temp.metric);

            image1.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[3].fctcode + ".png"));
            image2.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[6].fctcode + ".png"));
            image3.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[9].fctcode + ".png"));
            image4.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[12].fctcode + ".png"));
            image5.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[15].fctcode + ".png"));
            image6.Source = new BitmapImage(new Uri("ms-appx:///Assets/Weather/" + WeatherObj.hourly_forecast[18].fctcode + ".png"));

            for (byte i = 0; i <= 21; i++)
            {
                temp_raw[i] = Convert.ToInt32(WeatherObj.hourly_forecast[i].temp.metric);
            }


            vAvg   = temp_raw.Average();
            vScale = 20 / (Math.Abs(temp_raw.Max()) - Math.Abs(temp_raw.Min()));

            for (byte i = 0; i <= 21; i++)
            {
                double x_old = TempLine.Points.ElementAt(i + 1).X;
                y_temp_set[i] = 120 - Convert.ToInt32(Convert.ToInt32(WeatherObj.hourly_forecast[i].temp.metric) * vScale);
                TempLine.Points.RemoveAt(i + 1);
                TempLine.Points.Insert(i + 1, AsPoint(Convert.ToInt32(x_old), y_temp_set[i]));
            }

            Label_Temp1.SetValue(Canvas.TopProperty, (y_temp_set[3] - 25));
            image1.SetValue(Canvas.TopProperty, (y_temp_set[3] - 70));
            Label_Temp2.SetValue(Canvas.TopProperty, (y_temp_set[6] - 25));
            image2.SetValue(Canvas.TopProperty, (y_temp_set[6] - 70));
            Label_Temp3.SetValue(Canvas.TopProperty, (y_temp_set[9] - 25));
            image3.SetValue(Canvas.TopProperty, (y_temp_set[9] - 70));
            Label_Temp4.SetValue(Canvas.TopProperty, (y_temp_set[12] - 25));
            image4.SetValue(Canvas.TopProperty, (y_temp_set[12] - 70));
            Label_Temp5.SetValue(Canvas.TopProperty, (y_temp_set[15] - 25));
            image5.SetValue(Canvas.TopProperty, (y_temp_set[15] - 70));
            Label_Temp6.SetValue(Canvas.TopProperty, (y_temp_set[18] - 25));
            image6.SetValue(Canvas.TopProperty, (y_temp_set[18] - 70));

            Rect_Rain11.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[0].pop));  Rect_Rain11.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[0].pop));
            Rect_Rain12.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[1].pop));  Rect_Rain12.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[1].pop));
            Rect_Rain13.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[2].pop));  Rect_Rain13.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[2].pop));
            Rect_Rain21.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[3].pop));  Rect_Rain21.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[3].pop));
            Rect_Rain22.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[4].pop));  Rect_Rain22.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[4].pop));
            Rect_Rain23.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[5].pop));  Rect_Rain23.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[5].pop));
            Rect_Rain31.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[6].pop));  Rect_Rain31.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[6].pop));
            Rect_Rain32.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[7].pop));  Rect_Rain32.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[7].pop));
            Rect_Rain33.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[8].pop));  Rect_Rain33.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[8].pop));
            Rect_Rain41.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[9].pop));  Rect_Rain41.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[9].pop));
            Rect_Rain42.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[10].pop)); Rect_Rain42.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[10].pop));
            Rect_Rain43.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[11].pop)); Rect_Rain43.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[11].pop));
            Rect_Rain51.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[12].pop)); Rect_Rain51.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[12].pop));
            Rect_Rain52.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[13].pop)); Rect_Rain52.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[13].pop));
            Rect_Rain53.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[14].pop)); Rect_Rain53.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[14].pop));
            Rect_Rain61.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[15].pop)); Rect_Rain61.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[15].pop));
            Rect_Rain62.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[16].pop)); Rect_Rain62.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[16].pop));
            Rect_Rain63.SetValue(Canvas.HeightProperty, Convert.ToInt32(WeatherObj.hourly_forecast[17].pop)); Rect_Rain63.SetValue(Canvas.TopProperty, 100 - Convert.ToInt32(WeatherObj.hourly_forecast[17].pop));

            // Current Weather
            image_cur.Source   = new BitmapImage(new Uri("ms-appx:///Assets/Weather/big/" + WeatherObj.current_observation.icon + ".png"));
            Label_CurTemp.Text = WeatherObj.current_observation.temp_c + "°C";
            Label_CurFeel.Text = "Feels like " + WeatherObj.current_observation.feelslike_c + "°C";
            Label_CurPerc.Text = "The weather is " + WeatherObj.current_observation.weather.ToLower() + " with a forecasted percipitation of " + WeatherObj.current_observation.precip_today_metric + "mm. " + "The wind blows from " + WeatherObj.current_observation.wind_dir.ToLower() + " direction with " + WeatherObj.current_observation.wind_kph + "kmh.";

            Int32[] rain_forecast = new Int32[] { Convert.ToInt32(WeatherObj.hourly_forecast[0].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[1].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[2].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[3].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[4].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[5].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[6].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[7].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[8].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[9].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[10].pop),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[11].pop) };

            Int32[] wind_forecast = new Int32[] { Convert.ToInt32(WeatherObj.hourly_forecast[0].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[1].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[2].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[3].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[4].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[5].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[6].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[7].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[8].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[9].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[10].wspd.metric),
                                                  Convert.ToInt32(WeatherObj.hourly_forecast[11].wspd.metric) };

            if (DateTime.Now.Hour < 12)
            {
                s1 = "Good morning! ";
            }
            else
            {
                s1 = "Hi there! ";
            }
            if (rain_forecast.Max() > 20)
            {
                s2 = "Stay dry, it might rain";
                if (wind_forecast.Average() > 10)
                {
                    s3 = " and look out for flying cows, it's windy!";
                }
                else
                {
                    s3 = ".";
                }
            }
            else
            {
                s2 = "A dry day is forcasted, enjoy";
                if (wind_forecast.Average() > 10)
                {
                    s3 = ". But look out for flying cows, it's windy!";
                }
                else
                {
                    s3 = ".";
                }
            }
            Label_CurPerc.Text = s1 + s2 + s3;
        }
Пример #4
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            WeatherpagePrograssRing.IsActive   = true;
            WeatherpagePrograssRing.Visibility = Visibility.Visible;
            TempHighFontIcon.Visibility        = Visibility.Collapsed;
            TempLowFontIcon.Visibility         = Visibility.Collapsed;
            AqiTblock.Visibility = Visibility.Collapsed;

            if (MyNetHelper.IsNetAdapterWork() != true)
            {
                var dialog = new MessageDialog("请检查网络适配器是否打开且正常工作", "网络适配器错误");
                await dialog.ShowAsync();
            }
            else if (MyNetHelper.IsNetConnected() != true)
            {
                var dialog = new MessageDialog("请联系当地网络运营服务商", "网络连接错误");
                await dialog.ShowAsync();
            }
            else
            {
                if (geoposition == null)
                {
                    try
                    {
                        geoposition = await MyGeopositionHelper.GetGeopositionasync();

                        if (geoposition != null)
                        {
                            IsUnauthorizedAccess = false;//
                        }
                    }
                    catch (System.UnauthorizedAccessException)
                    {
                        MyMessageDialogHelper.ShowUnauthorizedAccessMessageAsync();
                    }
                    if (IsUnauthorizedAccess == false && Pageloadnum != 0)      //如果不是第一次访问
                    {
                        if (LastHourOfTime - System.DateTime.Now.Date.Hour > 2) //时间距离上次访问是否大于2小时
                        {
                            rootObject = await MyWeatherHelper.GetWeatherRootObjectAsync(APIkey, geoposition.Coordinate.Point.Position.Latitude, geoposition.Coordinate.Point.Position.Longitude);

                            Pageloadnum++;
                            LastHourOfTime = System.DateTime.Now.Date.Hour;
                        }
                    }
                    else
                    {
                        rootObject = await MyWeatherHelper.GetWeatherRootObjectAsync(APIkey, 39.088, 117.696184);

                        Pageloadnum++;
                    }
                }

                if (rootObject.msg != "ok")
                {
                    MyMessageDialogHelper.ShowApiErrorMessageAsync(rootObject.status, rootObject.msg);
                }
                else
                {
                    todayWeather.CityName           = rootObject.result.city;                //天津
                    todayWeather.Temp               = rootObject.result.temp + "°";          //23
                    todayWeather.TempHigh           = rootObject.result.temphigh + "°";      //30
                    todayWeather.TempLow            = rootObject.result.templow + "°";       //10
                    todayWeather.WeatherDescription = rootObject.result.weather;             //小雨
                    todayWeather.LastUpdateTime     = rootObject.result.updatetime;          //2018-04-12
                    todayWeather.AirQualityIndex    = rootObject.result.aqi.aqi;             //83
                    todayWeather.AqiLevel           = "级别:" + rootObject.result.aqi.quality; //良
                    //todayWeather.Icon = $"ms-appx:///Assets/weathercn02/{rootObject.result.img}.png";              //0.png
                    todayWeather.Icon                = string.Format($"ms-appx:///Assets/weathercn02/{rootObject.result.img}.png");
                    todayWeather.AqiColor            = rootObject.result.aqi.aqiinfo.color;      //#FF7E00
                    todayWeather.Humidity            = "湿度:" + rootObject.result.humidity + "%"; //83
                    DaliyWeatherListView.ItemsSource = DaliyWeather.GetWeathers(rootObject);
                }
                WeatherpagePrograssRing.IsActive   = false;
                WeatherpagePrograssRing.Visibility = Visibility.Collapsed;
                TempHighFontIcon.Visibility        = Visibility.Visible;
                TempLowFontIcon.Visibility         = Visibility.Visible;
                AqiTblock.Visibility = Visibility.Visible;
            }
        }