Weather Information is important for planning our day-to-day activities. Reading this article, you will learn to retrieve weather details using API key from openweathermap.org in Xamarin.Forms application, for Android and Universal Windows Platform.
The following important tools are required for developing the UWP.
- Windows 10 (Recommended)
- Visual Studio 2017 Community (https://www.visualstudio.com/downloads/ )
- Get a free Weather API key from http://openweathermap.org/appid
Now, we can discuss step by step app development.
Step 1
Open Visual Studio 2017 and go to Start -> New Project -> Cross-Platform (under Visual C#) -> Cross Platform App (Xamarin) -> Give the suitable name for your app (XamWeather) -> OK.
Step 2
Select the Cross-Platform template as a Blank APP. Set UI Technology as Forms and Sharing as PCL. Visual Studio creates 4 projects (Portable, Droid, iOS, UWP) and displays Getting Started.XamarinPage.
Step 3
For User View, in MainPage.Xaml Page, add the label control for title inside StackLayout.
- <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
- <Label Text="Weather App Using Xamarin Forms" FontSize="20" VerticalOptions="Center" HorizontalOptions="Center"/>
- </StackLayout>
Add Label, Entry, and button controls for getting PINCODE from the user.
- <StackLayout HorizontalOptions="Start" Margin="10,10,0,0" WidthRequest="400">
- <Label Text="Enter Your PIN Code" FontAttributes="Bold" TextColor="White" Margin="10" x:Name="lblSearch" />
- <Label Text="PIN Code" TextColor="White" Margin="10" x:Name="lblPinCode" />
- <StackLayout Orientation="Horizontal">
- <Entry WidthRequest="100" x:Name="entPinCode" />
- <Button Text="Get Weather Info" x:Name="btnGetWeather" /> </StackLayout>
- </StackLayout>
Add the Label Controls for displaying Location, Temperature, Sunrise, Sunset, Wind Speed, and Humidity.
- <StackLayout VerticalOptions="StartAndExpand">
- <Label Text="Location" TextColor="Black" FontSize="14" />
- <Label Text="" Margin="10,0,0,10" x:Name="txtLocation" />
- <Label Text="Temperature" TextColor="Black" FontSize="14" />
- <Label Text="" Margin="10,0,0,10" x:Name="txtTemperature" />
- <Label Text="Sunrise" TextColor="Black" FontSize="14" />
- <Label Text="" Margin="10,0,0,10" x:Name="txtSunrise" />
- <Label Text="Sunset" TextColor="Black" FontSize="14" />
- <Label Text="" Margin="10,0,0,10" x:Name="txtSunset" />
- <Label Text="Wind Speed" TextColor="Black" FontSize="14" />
- <Label Text="" Margin="10,0,0,10" x:Name="txtWind" />
- <Label Text="Humidity" TextColor="Black" FontSize="14" />
- <Label Text="" Margin="10,0,0,10" x:Name="txtHumidity" />
- </StackLayout>
Step 4
For performing the HTTP request and response, add the Newton.json file's reference.
Right-click the Solution(XamWeather)->Manage NuGet packages for Solution.
Browse and install the reference.
Step 5
Add the following class code for data binding (store the Weather details) in MainPage.Xaml.cs.
- public class Weather {
- public string Title {
- get;
- set;
- }
- public string Temperature {
- get;
- set;
- }
- public string Wind {
- get;
- set;
- }
- public string Humidity {
- get;
- set;
- }
- public string Visibility {
- get;
- set;
- }
- public string Sunrise {
- get;
- set;
- }
- public string Sunset {
- get;
- set;
- }
- public Weather() {
- this.Title = " ";
- this.Temperature = " ";
- this.Wind = " ";
- this.Humidity = " ";
- this.Visibility = " ";
- this.Sunrise = " ";
- this.Sunset = " ";
- }
- }
Step 6
Add the following namespace and code for btnGetWeather_Click (send the PIN code detail and retrive the information) Event method.
- using Newtonsoft.Json;
- using System.Net.Http;
- private async void btnGetWeather_Click(object sender, EventArgs e) {
- if (!String.IsNullOrEmpty(entPinCode.Text)) {
- Weather weather = await GetWeather(entPinCode.Text);
- if (weather != null) {
- txtLocation.Text = weather.Title;
- txtTemperature.Text = weather.Temperature;
- txtWind.Text = weather.Wind;
- txtHumidity.Text = weather.Humidity;
- txtSunrise.Text = weather.Sunrise;
- txtSunset.Text = weather.Sunset;
- btnGetWeather.Text = "Search Again";
- }
- }
- }
- public static async Task < Weather > GetWeather(string pinCode) {
- string key = "Your Key";
- string queryString = "http://api.openweathermap.org/data/2.5/weather?zip=" + pinCode + ",in&appid=" + key + "&units=imperial";
- if (key != " Your Key ") {
- throw new ArgumentException("Get you API key from openweathermap.org/appid and assign it in the 'key' variable.");
- }
- dynamic results = await getDataFromService(queryString).ConfigureAwait(false);
- if (results["weather"] != null) {
- Weather weather = new Weather();
- weather.Title = (string) results["name"];
- weather.Temperature = (string) results["main"]["temp"] + " F";
- DateTime time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
- DateTime sunrise = time.AddSeconds((double) results["sys"]["sunrise"]);
- DateTime sunset = time.AddSeconds((double) results["sys"]["sunset"]);
- weather.Sunrise = sunrise.ToString() + " UTC";
- weather.Sunset = sunset.ToString() + " UTC";
- weather.Wind = (string) results["wind"]["speed"] + " mph";
- weather.Humidity = (string) results["main"]["humidity"] + " %";
- return weather;
- } else {
- return null;
- }
- }
- public static async Task < dynamic > getDataFromService(string pQueryString) {
- HttpClient client = new HttpClient();
- var response = await client.GetAsync(pQueryString);
- dynamic data = null;
- if (response != null) {
- string json = response.Content.ReadAsStringAsync().Result;
- data = JsonConvert.DeserializeObject(json);
- }
- return data;
- }
Step 7
Deploy your app to Android Emulator and Local Machine (UWP). The output of the XamWeather App is shown below.
Summary
Now, you have successfully retrieved Weather details using API key from openweathermap.org in Xamarin.Forms application under cross-platform application development.