Friday, 1 August 2025

MAUI Weather App with GPS Location

MAUI Weather App with GPS Location


✅ Uses GPS to get current location,

✅ Fetches live weather updates for that location.

I'll walk you through the full solution, with all the pieces: permissions, GPS, API call, and UI.


🌍 MAUI Weather App with GPS Location

πŸ“² What It Does:

  • Gets the user's current location (latitude & longitude)

  • Sends location to OpenWeatherMap API

  • Displays live weather data for that location


✅ Step 1: Setup

1.1 Create MAUI App


dotnet new maui -n GpsWeatherApp cd GpsWeatherApp

πŸ” Step 2: Add Permissions

πŸ”Έ Android → Platforms/Android/AndroidManifest.xml

Inside <manifest>:


<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

πŸ”Έ iOS → Platforms/iOS/Info.plist

Inside <dict>:


<key>NSLocationWhenInUseUsageDescription</key> <string>This app needs your location to show weather updates.</string>

πŸ”§ Step 3: Add Weather + GPS Services

3.1 Weather Model

Models/WeatherInfo.cs


public class WeatherInfo { public Main main { get; set; } public List<Weather> weather { get; set; } public string name { get; set; } } public class Main { public float temp { get; set; } public int humidity { get; set; } } public class Weather { public string main { get; set; } public string description { get; set; } }

3.2 Weather Service

Services/WeatherService.cs


using System.Net.Http.Json; public class WeatherService { private const string ApiKey = "YOUR_API_KEY"; // Replace with your OpenWeatherMap API Key private readonly HttpClient _http; public WeatherService(HttpClient httpClient) { _http = httpClient; } public async Task<WeatherInfo?> GetWeatherAsync(double lat, double lon) { string url = $"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={ApiKey}&units=metric"; return await _http.GetFromJsonAsync<WeatherInfo>(url); } }

3.3 Register Services

MauiProgram.cs


builder.Services.AddSingleton<HttpClient>(); builder.Services.AddSingleton<WeatherService>();

πŸ“± Step 4: Build the UI

MainPage.xaml


<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" x:Class="GpsWeatherApp.MainPage" Title="Weather App"> <VerticalStackLayout Padding="20" Spacing="15"> <Label Text="Live Weather" FontSize="28" HorizontalOptions="Center" /> <Button Text="Get Weather via GPS" Clicked="OnGetWeatherClicked" /> <Label x:Name="WeatherResultLabel" Text="Your weather info will appear here." FontSize="18" TextColor="DarkSlateBlue" HorizontalOptions="Center" /> </VerticalStackLayout> </ContentPage>

πŸ’‘ Step 5: Add Logic

MainPage.xaml.cs


using Microsoft.Maui.ApplicationModel; using GpsWeatherApp.Services; public partial class MainPage : ContentPage { private readonly WeatherService _weatherService; public MainPage(WeatherService weatherService) { InitializeComponent(); _weatherService = weatherService; } private async void OnGetWeatherClicked(object sender, EventArgs e) { try { var location = await Geolocation.GetLocationAsync(new GeolocationRequest { DesiredAccuracy = GeolocationAccuracy.High, Timeout = TimeSpan.FromSeconds(10) }); if (location == null) { WeatherResultLabel.Text = "Location unavailable."; return; } var weather = await _weatherService.GetWeatherAsync(location.Latitude, location.Longitude); if (weather != null) { WeatherResultLabel.Text = $"πŸ“ {weather.name}\n" + $"🌑 Temp: {weather.main.temp} °C\n" + $"πŸ’§ Humidity: {weather.main.humidity}%\n" + $"⛅ Condition: {weather.weather[0].description}"; } else { WeatherResultLabel.Text = "Could not fetch weather data."; } } catch (PermissionException) { WeatherResultLabel.Text = "Location permission not granted."; } catch (Exception ex) { WeatherResultLabel.Text = $"Error: {ex.Message}"; } } }

🌐 Step 6: Get Your OpenWeatherMap API Key

  1. Go to https://openweathermap.org/api

  2. Create an account

  3. Generate a free API key

  4. Replace "YOUR_API_KEY" in the service


πŸš€ Step 7: Run and Test

Run on:

  • Android Emulator or Device (preferred for GPS)

  • Windows (limited GPS support, returns null unless location enabled)

  • iOS (if using Mac)


✅ You're Done!

Final Features:

  • Uses device GPS

  • Fetches live weather data

  • Displays data in clean UI

  • Resilient to permission issues

No comments:

Post a Comment

Cricket Streaming MAUI App: Complete Solution

This document outlines a comprehensive solution for building a cricket streaming MAUI app with subscription plans, geo-restrictions, and pre...

Ads2