Advertisement
KristianIvanov00

Untitled

Mar 23rd, 2024
558
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1.  
  2. namespace UnweWeatherApp;
  3.  
  4.  
  5. public partial class MainPage : ContentPage
  6. {
  7.     OpenWeatherService _openWeatherService;
  8.     public MainPage()
  9.     {
  10.         InitializeComponent();
  11.         _openWeatherService = new OpenWeatherService();
  12.         GetWeatherWithGeoLocation();
  13.  
  14.     }
  15.     string GenerateRequestUri(string endpoint)
  16.     {
  17.         string requestUri = endpoint;
  18.         requestUri += $"?q={_cityEntry.Text}";
  19.         requestUri += "&units=metric";
  20.         requestUri += $"&APPID={Constants.OpenWeatherMapAPIKey}";
  21.         return requestUri;
  22.     }
  23.  
  24.     public async void OnGetWeatherButtonClicked(object sender, EventArgs e)
  25.     {
  26.         if (!string.IsNullOrWhiteSpace(_cityEntry.Text))
  27.         {
  28.             WeatherData weatherData = await _openWeatherService.GetWeatherData(GenerateRequestUri(Constants.OpenWeatherMapEndpoint));
  29.             _weatherIcon.Source = "https://openweathermap.org/img/wn/" + weatherData.weather[0].icon + "@2x.png";
  30.             BindingContext = weatherData;
  31.         }
  32.     }
  33.    
  34.     public async void GetWeatherWithGeoLocation()
  35.     {
  36.         var location = await Geolocation.GetLocationAsync();
  37.  
  38.         if (location != null)
  39.         {
  40.             var lat = location.Latitude;
  41.             var lon = location.Longitude;
  42.             WeatherData weatherData = await _openWeatherService.GetWeatherData(GenerateRequestUriGeo(Constants.OpenWeatherMapEndpoint, lat, lon));
  43.             _weatherIcon.Source = "https://openweathermap.org/img/wn/" + weatherData.weather[0].icon + "@2x.png";
  44.             BindingContext = weatherData;
  45.         }
  46.     }
  47.  
  48.     string GenerateRequestUriGeo(string endpoint, double lati, double longt)
  49.     {
  50.         string requestUri = endpoint;
  51.         requestUri += $"?lat={lati}";
  52.         requestUri += $"&lon={longt}";
  53.         requestUri += "&units=imperial";
  54.         requestUri += $"&APPID={Constants.OpenWeatherMapAPIKey}";
  55.         return requestUri;
  56.     }
  57. }
  58.  
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement