Para finalizar este proyecto, crearemos el formulario de la interfaz gráfica, y haremos los ajustes finales para tener nuestra aplicación corriendo.
En primer lugar, crearemos la última carpeta que nos hace falta llamada View:
En la nueva carpeta crearé un nuevo elemento del tipo Forms Xaml Page al cual llamaremos MainPage:
En el formulario creado, usaremos el siguiente código para el archivo MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="JsonWebServices.View.MainPage"> <ContentPage.Content> <StackLayout Padding="30"> <StackLayout Orientation="Horizontal"> <Label Text="Latitude" WidthRequest="130"></Label> <Entry x:Name="txtLatitude" WidthRequest="150"></Entry> </StackLayout> <StackLayout Orientation="Horizontal"> <Label Text="Longitude" WidthRequest="130"></Label> <Entry x:Name="txtLongitude" WidthRequest="150"></Entry> </StackLayout> <Button x:Name="btnSearch" Clicked="OnClicked" WidthRequest="75" Text="Search" TextColor="White" BackgroundColor="Blue"></Button> <StackLayout Orientation="Horizontal"> <Label Text="Location: " TextColor="Green" WidthRequest="130"></Label> <Label Text="{Binding StationName}"></Label> </StackLayout> <StackLayout Orientation="Horizontal"> <Label Text="Elevation: " TextColor="Green" WidthRequest="130"></Label> <Label Text="{Binding Elevation}"></Label> </StackLayout> <StackLayout Orientation="Horizontal"> <Label Text="Temperature: " TextColor="Green" WidthRequest="130"></Label> <Label Text="{Binding Temperature}"></Label> </StackLayout> <StackLayout Orientation="Horizontal"> <Label Text="Humidity: " TextColor="Green" WidthRequest="130"></Label> <Label Text="{Binding Humidity}"></Label> </StackLayout> </StackLayout> </ContentPage.Content> </ContentPage>
Por otra parte, en el archivo MainPage.xaml.cs, debemos definir una variable que será la instancia del ViewModel de la siguiente manera:
public MainPageViewModel vm;
Esta variable la inicializaremos dentro del constructor:
vm = new MainPageViewModel();
De igual forma, dentro del constructor debemos asignar el contexto de datos a dicha variable de la siguiente forma:
BindingContext = vm;
Por último, crearemos el manejador de eventos que hará la llamada al servicio web, en primer lugar, obtendremos la información de las cajas de texto, paso seguido definiremos la url del servicio web, y al último haremos la llamada a través del método especificado:
public async void OnClicked(object sender, EventArgs e) { var longitude = double.Parse(txtLongitude.Text); var latitude = double.Parse(txtLatitude.Text); var url = string.Format(@"http://api.geonames.org/findNearByWeatherJSON?formatted=true&lat={0}&lng={1}&username=demo&style=full", latitude, longitude); await vm.GetWeatherAsync(url); }
quedando de la siguiente manera el archivo:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JsonWebServices.ViewModel; using Xamarin.Forms; namespace JsonWebServices.View { public partial class MainPage : ContentPage { public MainPageViewModel vm; public MainPage() { vm = new MainPageViewModel(); BindingContext = vm; InitializeComponent(); } public async void OnClicked(object sender, EventArgs e) { var longitude = double.Parse(txtLongitude.Text); var latitude = double.Parse(txtLatitude.Text); var url = string.Format(@"http://api.geonames.org/findNearByWeatherJSON?formatted=true&lat={0}&lng={1}&username=demo&style=full", latitude, longitude); await vm.GetWeatherAsync(url); } } }
Por último, modificaremos el constructor de la clase App para que asigne a la página MainPage como la página principal:
public App() { // The root page of your application MainPage = new MainPage(); }
Una vez terminada la codificación, podemos buscar coordenadas en cualquier aplicación de mapas para probar:
Ejecutaremos la aplicación e Insertaremos estas coordenadas, al presionar el botón search, nos mostrará el resultado correspondiente:
Definitivamente hay cosas que pueden ser mejoradas, pero queda como tarea para la casa, Espero que esta serie les haya gustado y servido. Recuerden que todo el proyecto lo pueden descargar desde aquí.
Saludos.