- [DEVEXPRESS] Hướng dẫn bật tính năng Scroll Pixcel in Touch trên GridView
- [DEVEXPRESS] Hướng dẫn sử dụng TileBar viết ứng dụng duyệt hình ảnh Winform
- [DEVEXPRESS] Tô màu border TextEdit trên Winform
- [C#] Lấy dữ liệu từ Console Write hiển thị lên textbox Winform
- [C#] Hiển thị Progress bar trên Window Console
- [C#] Di chuyển control Runtime và lưu layout trên winform
- [SQLSERVER] Sử dụng hàm NULL IF
- [C#] Chia sẽ source code mã đi tuần bằng giao diện Winform
- [C#] Flash Window in Taskbar Winform
- Download và Giải nén tập tin File sử dụng Powershell
- [C#] Hướng dẫn cách lấy thông tin đăng nhập tài khoản và mật khẩu web browser trên windows
- [VB.NET] CRUD Thêm xóa sửa tìm kiếm Realtime FireBase
- [C#] Hiển thị thông báo Toast Message trong lập trình Winform
- [C#] Cấu hình định dạng ngày tháng, thời gian trên Windows cho ứng dụng Winform
- [C#] Rút gọn đường dẫn link url với TinyURL API
- [C#] Hướng dẫn cách bo tròn winform with Radius
- [C#] Chia sẽ class BackGroundOverlay Show Modal cho Winform
- [C#] Hướng dẫn Flip Image Winform
- [C#] Invoke là gì? cách sử dụng phương thức Invoke()
- [C#] Hướng dẫn chia sẽ file, folder từ ứng dụng sang Zalo Chat
[C#] Hướng dẫn lấy dữ liệu dự báo thời tiết từ OpenWeatherMap Api
Xin chào các bạn, hôm nay mình sẽ hướng dẫn cho các bạn lấy dữ liệu dự báo thời tiết sử dụng API OpenWeatherMap C# hoàn toàn miễn phí trong lập trình Winform.
OpenWeatherMap API này cung cấp dịch vụ dữ liệu thời tiết và dự báo miễn phí, thích hợp cho bất kỳ dịch vụ bản đồ như các ứng dụng web và điện thoại thông minh. Ý tưởng được lấy cảm hứng từ OpenStreetMap và Wikipedia nhằm cung cấp thông tin miễn phí và sẵn có cho mọi người.
OpenWeatherMap cung cấp nhiều dữ liệu thời tiết như bản đồ thời tiết hiện tại, dự báo tuần, lượng mưa, gió, mây, dữ liệu từ các trạm thời tiết và nhiều thứ khác. Dữ liệu thời tiết được nhận từ các dịch vụ phát sóng khí tượng toàn cầu và hơn 40.000 trạm khí tượng.
Bạn có thể nhận được bất kỳ dữ liệu thời tiết nào cho ứng dụng của bạn bằng cách sử dụng chuỗi JSON
hoặc XML
.
Giao diện ứng dụng dự báo thời tiết c#:

Để làm được bài này, rất đơn giản đầu tiên các bạn truy cập vào trang web openweathermap để đăng ký một tài khoản và lấy API để truy vấn.
Link đăng ký Api openweathermap: http://home.openweathermap.org/users/sign_in
Sau khi đăng ký xong, các bạn chọn tab Api để lấy Api key điền vào ứng dụng ở source code C# bên dưới.

Source code C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.IO;
using System.Globalization;
namespace dubaothoitiet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// http://home.openweathermap.org/users/sign_in -- link đăng ký lấy API
private const string API_KEY = "c7055ce01673bc05bf8af1cb09e60bd2";
private const string CurrentUrl =
"http://api.openweathermap.org/data/2.5/weather?" +
"@QUERY@=@LOC@&mode=xml&units=imperial&APPID=" + API_KEY;
private const string ForecastUrl =
"http://api.openweathermap.org/data/2.5/forecast?" +
"@QUERY@=@LOC@&mode=xml&units=imperial&APPID=" + API_KEY;
private string[] QueryCodes = { "q", "zip", "id", };
private void Form1_Load(object sender, EventArgs e)
{
cboQuery.Items.Add("City");
cboQuery.Items.Add("ZIP");
cboQuery.Items.Add("ID");
cboQuery.SelectedIndex = 0;
}
private void btnForecast_Click(object sender, EventArgs e)
{
string url = ForecastUrl.Replace("@LOC@", txtLocation.Text);
url = url.Replace("@QUERY@", QueryCodes[cboQuery.SelectedIndex]);
using (WebClient client = new WebClient())
{
try
{
DisplayForecast(client.DownloadString(url));
}
catch (WebException ex)
{
DisplayError(ex);
}
catch (Exception ex)
{
MessageBox.Show("Unknown error\n" + ex.Message);
}
}
}
private void DisplayForecast(string xml)
{
XmlDocument xml_doc = new XmlDocument();
xml_doc.LoadXml(xml);
XmlNode loc_node = xml_doc.SelectSingleNode("weatherdata/location");
txtCity.Text = loc_node.SelectSingleNode("name").InnerText;
txtCountry.Text = loc_node.SelectSingleNode("country").InnerText;
XmlNode geo_node = loc_node.SelectSingleNode("location");
txtLat.Text = geo_node.Attributes["latitude"].Value;
txtLong.Text = geo_node.Attributes["longitude"].Value;
txtId.Text = geo_node.Attributes["geobaseid"].Value;
lvwForecast.Items.Clear();
char degrees = (char)176;
foreach (XmlNode time_node in xml_doc.SelectNodes("//time"))
{
DateTime time =
DateTime.Parse(time_node.Attributes["from"].Value,
null, DateTimeStyles.AssumeUniversal);
XmlNode temp_node = time_node.SelectSingleNode("temperature");
string temp = temp_node.Attributes["value"].Value;
ListViewItem item = lvwForecast.Items.Add(time.DayOfWeek.ToString());
item.SubItems.Add(time.ToShortTimeString());
item.SubItems.Add(temp + degrees);
}
}
private void DisplayError(WebException exception)
{
try
{
StreamReader reader = new StreamReader(exception.Response.GetResponseStream());
XmlDocument response_doc = new XmlDocument();
response_doc.LoadXml(reader.ReadToEnd());
XmlNode message_node = response_doc.SelectSingleNode("//message");
MessageBox.Show(message_node.InnerText);
}
catch (Exception ex)
{
MessageBox.Show("Unknown error\n" + ex.Message);
}
}
}
}
HAVE FUN :)