question

Win95Dev-7436 avatar image
0 Votes"
Win95Dev-7436 asked Castorix31 commented

C# Label shows Weather Information

Hey
I want to create a simple weather app. A Label should show if its cloudy or sunny or rain and all the other things and the temperature in celsius. But because im a noob i dont know. So please help. Thanks

windows-forms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

There is replacement for a paid service for obtaining this information although the following will be good enough. I did not do the image aspect.

https://github.com/karenpayneoregon/windows-forms-csharp/tree/master/OpenWeatherMapApp

  • Requires Json.Net

  • Code below does not show required classes which are included.

Form code

 using System;
 using System.Net.Http;
 using System.Windows.Forms;
 using Newtonsoft.Json;
 using OpenWeatherMapApp.Classes;
    
 namespace OpenWeatherMapApp
 {
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
         }
    
         private async void GetButton_Click(object sender, EventArgs e)
         {
             var http = new HttpClient();
    
             /*-------------------------------------
              * Set up to your long lat for your area
              -------------------------------------*/
                
             var url = "https://forecast.weather.gov/MapClick.php?lat=44.9429&lon=-123.0351&FcstType=json";
                
             http.DefaultRequestHeaders.Add(
                 "User-Agent", 
                 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 " + 
                      "(KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36");
                
             var response = await http.GetAsync(url);
                
             if (response.IsSuccessStatusCode)
             {
                 var json = await response.Content.ReadAsStringAsync();
                 var weather = JsonConvert.DeserializeObject<WeatherRoot>(json);
    
    
                 weatherLabel.InvokeIfRequired(label =>
                 {
                     label.Text = $"{weather.Current.Temperature} degrees, {weather.Current.Weather}";
                 });
             }
         }
     }
 }





5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Castorix31 avatar image
0 Votes"
Castorix31 answered Castorix31 commented

If you want weather from your current location, you must first get Latitute/Longitude, then you can read the weather from "tile-service.weather.microsoft.com"

A test =>

119591-weather.jpg


 using System.Xml;
 // Add reference to : System.Device
 using System.Device.Location;
    
 public partial class Form1 : Form
 {
     public Form1()
     {
         //InitializeComponent();
         this.Load += new System.EventHandler(this.Form1_Load);
     }
    
     private void button1_Click(object sender, EventArgs e)
     {
         // https://docs.microsoft.com/en-us/dotnet/api/system.device.location.geocoordinate.latitude?view=netframework-4.8
         GeoCoordinateWatcher watcher;
         GeoCoordinate coordinate = null;
         watcher = new GeoCoordinateWatcher();
         watcher.PositionChanged += (sender1, e1) =>
         {
             coordinate = e1.Position.Location;
             watcher.Stop();
             if (coordinate != null)
             {
                 string sLocation = null;
                 string sTemperature = null;
                 string sWeather = null;
    
                 double nLatitute = coordinate.Latitude;
                 double nLongitude = coordinate.Longitude;
                 XmlTextReader reader = null;
                 try
                 {
                     string sLatitute = nLatitute.ToString().Replace(",", ".");
                     string sLongitude = nLongitude.ToString().Replace(",", ".");
                     string sAddress = String.Format("https://tile-service.weather.microsoft.com/livetile/front/{0},{1}", sLatitute, sLongitude);
                     int nCpt = 0;
                     reader = new XmlTextReader(sAddress);
                     reader.WhitespaceHandling = WhitespaceHandling.None;                      
                     while (reader.Read())
                     {
                         if (reader.NodeType == XmlNodeType.Text)
                         {
                             if (nCpt == 0)
                                 sLocation = reader.Value;
                             else if (nCpt == 1)
                                 sTemperature = reader.Value;
                             else if (nCpt == 2)
                                 sWeather = reader.Value;
                             nCpt++;
                         }                        
                     }
                 }
                 finally
                 {
                     if (reader != null)
                         reader.Close();
                 }
                 string sTemperatureF = sTemperature.Replace("°", "");
                 double nTemperatureC = (Double.Parse(sTemperatureF) -32.0)*(double)5/9;
                 string sTemperatureC = nTemperatureC.ToString("#.#");
                 label1.Text = String.Format("{0}, {1}F({2}°C), {3}", sLocation, sTemperature, sTemperatureC, sWeather);
             }
         };
         watcher.Start();        
     }
    
     private System.Windows.Forms.Button button1;
     private System.Windows.Forms.Label label1;
     private void Form1_Load(object sender, EventArgs e)
     {
         this.button1 = new System.Windows.Forms.Button();
         this.label1 = new System.Windows.Forms.Label();
    
         this.button1.Location = new System.Drawing.Point(40, 76);
         this.button1.Name = "button1";
         this.button1.Size = new System.Drawing.Size(75, 23);
         this.button1.Text = "Get infos";
         this.button1.UseVisualStyleBackColor = true;
         this.button1.Click += new System.EventHandler(this.button1_Click);
    
         this.label1.AutoSize = true;
         this.label1.Location = new System.Drawing.Point(130, 81);
         this.label1.Name = "label1";
         this.label1.Size = new System.Drawing.Size(115, 13);
         this.label1.Text = "[Location, T°, weather]";
    
         this.Name = "Form1";
         this.ClientSize = new System.Drawing.Size(425, 182);
         this.Controls.Add(this.label1);
         this.Controls.Add(this.button1);
     }
 }




weather.jpg (27.1 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for the code but the information should show when you start the program without pressing a button

0 Votes 0 ·

The button was just for testing...
Just move the code in Form1_Load for example

0 Votes 0 ·