Nucleus
OS integration

LocationNew

Read the device's position from Kotlin Multiplatform code, with one API on Windows, macOS, Linux, Android, iOS and the web.

View as Markdown

location reads the device's position. It is a Kotlin Multiplatform module: the same calls work on desktop, Android, iOS and the web.

locationmacOSWindowsLinuxAndroidiOSWebDesktop Gradle plugin: RecommendedDesktop window runtime: Not neededmacOS needs the location usage description and entitlement, otherwise access is denied.
PlatformBackend
WindowsWinRT Geolocator
macOSCore Location
LinuxXDG Location portal, else GeoClue 2
AndroidFramework LocationManager, fused provider on API 31+. No Play services
iOSCore Location
Web (js, wasmJs)W3C Geolocation API

Add the dependency

build.gradle.kts
// commonMain in a KMP project, dependencies { } in a JVM desktop app
implementation("dev.nucleusframework:nucleus.location:3.0.0")

nucleus-application does not bring it: add it yourself to call NucleusWindow.requestLocationAuthorization.

Get the position

import dev.nucleusframework.location.Geolocation

// One fix. A fix acquired in the last 5 minutes comes back without waiting.
val here = Geolocation.currentLocation(LocationAccuracy.Approximate, maxAge = 5.minutes)

// Fixes as the device moves, until the collecting coroutine is cancelled.
Geolocation.locationUpdates(minInterval = 2.seconds, minDistanceMeters = 10.0)
    .collect { location -> show(location.latitude, location.longitude) }
  • currentLocation measures a new fix by default (maxAge = Duration.ZERO). A positive maxAge lets the platform answer from its cache, at once, with isCached = true. timeout (30 s by default) bounds the whole request.
  • locationUpdates is cold: each collector opens its own platform session, which stops when the collection ends. Short outages are ridden out; the flow fails when access is denied or location becomes unavailable. minInterval and minDistanceMeters are hints.
  • Precise uses GNSS where there is one. Approximate is city level, often answered from Wi-Fi or the network.
  • Every member is safe to call from any thread.

Location carries latitude, longitude, timestampMillis and isCached, plus altitude, horizontalAccuracy, verticalAccuracy, bearing and speed, which are null when the platform did not measure them.

Ask for access

currentLocation and locationUpdates prompt on their own when access has not been decided yet, and throw LocationException(LocationError.AuthorizationDenied) when it is refused. To choose when the prompt appears, or to ask for background access, request it first:

when (Geolocation.requestAuthorization(LocationAccess.Foreground, LocationAccuracy.Precise)) {
    LocationAuthorization.Foreground, LocationAuthorization.Background -> startTracking()
    else -> explainWhyLocationHelps()
}

From a Nucleus window, window.requestLocationAuthorization(access, accuracy) attaches the Linux consent dialog to the window, through x11:<xid> or an xdg_foreign export on Wayland. Windows and macOS prompts belong to the system.

MemberNotes
authorization()NotDetermined, Denied, Restricted, Foreground or Background, without prompting
authorizationUpdates(pollInterval = 1.seconds)The current value, then every change, including one made in system settings
openSettings()Opens the system page that grants or revokes access. false on the web or a Linux desktop without one

Windows and Linux report NotDetermined until a request in the current process has been answered: they cannot tell "allowed" from "never asked" without asking. Desktop apps keep their access in the background, so macOS reports a grant as Background.

Set up each platform

macOS and iOS

Core Location prompts only an app whose Info.plist explains why: NSLocationWhenInUseUsageDescription, plus NSLocationAlwaysAndWhenInUseUsageDescription for background access. macOS also reads NSLocationUsageDescription.

build.gradle.kts
macOS {
    infoPlist {
        extraKeysRawXml = """
            <key>NSLocationUsageDescription</key>
            <string>Shows the weather where you are.</string>
            <key>NSLocationWhenInUseUsageDescription</key>
            <string>Shows the weather where you are.</string>
        """.trimIndent()
    }
}

The hardened runtime on macOS also needs the com.apple.security.personal-information.location entitlement, sandboxed or not. entitlementsFile replaces the plugin's defaults, so repeat the JVM keys (allow-jit, allow-unsigned-executable-memory, disable-library-validation) next to it. See Configure macOS entitlements.

Without the usage description or the entitlement, as in a ./gradlew run without a bundle, requestAuthorization returns NotDetermined at once and location calls fail with AuthorizationDenied, naming what is missing.

Windows

No manifest capability. Access follows Settings → Privacy & security → Location → Let desktop apps access your location. Windows 11 24H2 and later prompt on the first request.

Linux

The XDG Location portal is used whenever it is present, sandboxed or not: it shows the desktop's consent dialog. Without a portal, an unsandboxed app talks to GeoClue 2, which identifies it by its .desktop id (the installed entry, else NucleusApp.appId). A portal refusal is final: GeoClue is never tried behind it. The portal and GeoClue report no revocation, so authorizationUpdates only changes when a request in this process is answered.

Android

Declare the permissions you use; the library declares none:

AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- LocationAccuracy.Precise -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- LocationAccess.Background -->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

The prompt needs a resumed activity, which the library tracks through a ContentProvider merged into the manifest. Removing that provider disables the library. On Android 12 and later, a precise request shows the precise or approximate choice in one dialog. Background access is asked for separately after a foreground grant, as the platform requires.

Web

The page must be served over HTTPS or from localhost. Browsers prompt only when a position is requested, so requestAuthorization asks for one. authorization() reads the Permissions API and may report NotDetermined on its very first call. minInterval, minDistanceMeters and LocationAccess.Background are ignored.

Handle errors

LocationException.error is a LocationError:

ValueMeaning
AuthorizationDeniedThe user or the system refused access
TemporarilyUnavailableNo fix right now; retrying later may succeed
PermanentlyUnavailableLocation is off, or there is no location service
NetworkThe network-based provider could not be reached
TimeoutNo fix within the request's timeout
UnknownAnything the platform did not explain

Geolocation implements LocationProvider. Depend on the interface to substitute a fake in tests.

API reference

SymbolNotes
Geolocation.isAvailableWhether the platform has a reachable location service
currentLocation(accuracy = Precise, maxAge = ZERO, timeout = 30.seconds)suspend, one Location
locationUpdates(accuracy = Precise, minInterval = 1.seconds, minDistanceMeters = 0.0)Cold Flow<Location>
requestAuthorization(access = Foreground, accuracy = Precise)suspend, returns LocationAuthorization
authorization() / authorizationUpdates()LocationAuthorization / Flow<LocationAuthorization>
openSettings(): BooleanOpens the system location settings
NucleusWindow.requestLocationAuthorization(access, accuracy)In nucleus-application: parents the Linux consent dialog
Geolocation.requestAuthorization(LocationPortalParent(portalParent, keepAlive), …)JVM: the same without nucleus-application

What's next

Was this page helpful?
Edit on GitHub

Last updated on