maui-geolocation

Add geolocation to a .NET MAUI app using Microsoft.Maui.Devices.Sensors, covering single and continuous location retrieval, platform permissions (Android, iOS, macOS, Windows), accuracy levels, CancellationToken usage, mock location detection, and a DI-friendly service wrapper. Suitable for obtaining current location and location tracking; does not cover displaying location on maps, general permission handling, or address geocoding.

Last repository push
GitHub Stars
181
Forks
21
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "maui-geolocation" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-bc3482632e43637e398a96bc1b91b8df0251cb64437f9b496325aa1c85441bf8. Verify the upstream source and version against https://github.com/davidortinau/maui-skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Add geolocation to a .NET MAUI app using Microsoft.Maui.Devices.Sensors, covering single and continuous location retrieval, platform permissions (Android, iOS, macOS, Windows), accuracy levels, CancellationToken usage, mock location detection, and a DI-friendly service wrapper. Suitable for obtaining current location and location tracking; does not cover displaying location on maps, general permission handling, or address geocoding.

0 Downloads

Introduction source: third_party · davidortinau · 0.0.1 Reference

SkillPi interpretation

Tasks
`GetLocationAsync` can hang indefinitely if GPS is off, the device is indoors, or permissions are in a pending state. Always set a timeout.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: maui-geolocation
description: >
  Add geolocation capabilities to .NET MAUI apps using Microsoft.Maui.Devices.Sensors.
  Covers one-shot and continuous location, platform permissions (Android, iOS, macOS, Windows),
  accuracy levels, CancellationToken usage, mock-location detection, and a DI-friendly service wrapper.
  USE FOR: "geolocation", "GPS location", "get current location", "location permission",
  "continuous location", "location tracking", "GeolocationRequest", "mock location",
  "latitude longitude MAUI".
  DO NOT USE FOR: displaying locations on a map (use maui-maps),
  general permission handling (use maui-permissions), or geocoding addresses (use maui-maps).

.NET MAUI Geolocation

Critical: Always Pass a CancellationToken

GetLocationAsync can hang indefinitely if GPS is off, the device is indoors, or permissions are in a pending state. Always set a timeout.

// ❌ Hangs forever if no GPS fix is available
var location = await Geolocation.Default.GetLocationAsync(
    new GeolocationRequest(GeolocationAccuracy.High));

// ✅ Times out after 30 seconds
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var location = await Geolocation.Default.GetLocationAsync(
    new GeolocationRequest(GeolocationAccuracy.High), cts.Token);

Accuracy vs. Battery Trade-off

Use the lowest accuracy that satisfies your feature. Higher accuracy drains battery significantly faster — especially on Android.

Use case Recommended accuracy
City-level / weather Lowest or Low
Nearby search / store finder Medium
Turn-by-turn navigation High or Best

Platform Gotchas

iOS 14 reduced accuracy

Users can grant "approximate" location (accuracy > 1 km). Your app receives a location, but it may be useless for precision features.

  • Check location.Accuracy — values > 100 m likely indicate reduced precision.
  • Use GeolocationRequest.RequestFullAccuracy with a key matching NSLocationTemporaryUsageDescriptionDictionary in Info.plist to prompt for full accuracy.

Android: mock locations in security-sensitive flows

// ⚠️ Always check in security-sensitive flows (e.g., geofence, check-in)
if (location.IsFromMockProvider)
{
    // Reject — user is spoofing location
}

Android: Altitude 0.0 is not sea level

Some Android devices return 0.0 for Altitude when the GPS has no barometric sensor. Treat 0.0 as "unknown", not sea level.

Android 10+: background location requires separate permission

ACCESS_BACKGROUND_LOCATION must be requested separately from foreground permissions and triggers a distinct system dialog. Requesting it together with foreground permissions causes both to be denied on some devices.

GetLastKnownLocationAsync returns null

This is expected on first boot or after a location-data reset. Always fall back to GetLocationAsync:

// ✅ Cache-first with fresh fallback
var location = await geolocation.GetLastKnownLocationAsync();
if (location is null || location.Timestamp < DateTimeOffset.UtcNow.AddMinutes(-5))
{
    location = await geolocation.GetLocationAsync(
        new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10)), ct);
}

Permissions must be requested before any geolocation call

Call Permissions.RequestAsync<Permissions.LocationWhenInUse>() first, or catch PermissionException. Calling GetLocationAsync without permission throws on some platforms and returns null on others — inconsistent behaviour across platforms.


Continuous Listening: Don't Forget to Unsubscribe

Failing to remove the LocationChanged handler when stopping causes continued GPS usage and battery drain.

// ❌ Forgetting to unsubscribe — GPS stays active
public void StopTracking()
{
    Geolocation.Default.StopListeningForeground();
    // LocationChanged handler still fires!
}

// ✅ Always remove the event handler
public void StopTracking()
{
    Geolocation.Default.StopListeningForeground();
    Geolocation.Default.LocationChanged -= OnLocationChanged;
}

Checklist

  • [ ] CancellationToken passed to every GetLocationAsync call
  • [ ] Accuracy level matched to feature need (not blindly set to Best)
  • [ ] GetLastKnownLocationAsync null-check with GetLocationAsync fallback
  • [ ] Runtime permissions requested before first geolocation call
  • [ ] LocationChanged handler removed when stopping continuous listening
  • [ ] Android: ACCESS_BACKGROUND_LOCATION requested separately (if needed)
  • [ ] iOS: NSLocationTemporaryUsageDescriptionDictionary added for full-accuracy prompt
  • [ ] Android: IsFromMockProvider checked in security-sensitive flows

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供 .NET MAUI 地理定位的完整实现指南,涵盖单次/持续定位、权限处理、精度控制、异常处理、依赖注入封装等
  • 解决开发者在跨平台定位中的常见痛点(如 CancellationToken 超时、模拟位置检测、平台差异等)
  • 属于明确场景的通用工具,受众为 .NET MAUI 开发者,实用性强
Trigger Precision95/100

Highlights

  • frontmatter 中 description 字段完整定义了适用与不适用场景
  • 覆盖多种关键词变体(geolocation、GPS location、get current location、location permission、continuous location、location tracking、GeolocationRequest、mock location、latitude longitude MAUI)
  • 边界清晰
Structure and Standards90/100

Highlights

  • 文档结构清晰,分 Critical、Accuracy vs. Battery Trade-off、Platform Gotchas、Continuous Listening、Checklist 等章节
  • 每部分有具体代码示例和说明
  • frontmatter 完整,单文件约400行
Execution Reliability90/100

Highlights

  • 提供了关键可靠性保障(如 CancellationToken 防挂起、权限请求前置、事件处理器注销防内存泄漏、模拟位置检测、平台特定配置)
  • 覆盖主要异常场景
Evidence Verifiability (mean of the first four)90/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.