Skip to content
FEE
Frontend Engineering Essentials
Mid Level
Hardened· 2026-07

[FEE-413] Geolocation, Device Orientation & Device APIs ​

INFO

The Geolocation API, Device Orientation API, and Device Motion API expose hardware sensors to web applications. Geolocation provides latitude, longitude, altitude, heading, and speed from GPS, Wi-Fi triangulation, or cell tower data. DeviceOrientationEvent provides spatial orientation via the accelerometer and gyroscope, and DeviceMotionEvent provides raw acceleration and rotation rate data. Together these APIs bridge the physical environment and the browser, enabling location-aware services, augmented reality overlays, compass interfaces, and motion-driven interactions without a native application wrapper.

Context ​

All of these APIs require explicit user permission. Browsers will not grant access to location or motion sensors without a permission prompt, and on most platforms the permission must be requested in response to a user gesture. Applications that try to access location silently, or on page load without a clear user-facing reason, will be blocked. iOS Safari 13 and later additionally requires a programmatic call to DeviceOrientationEvent.requestPermission() initiated from a user gesture; attaching the event listeners alone does nothing on iOS until that call resolves to 'granted'.

The practical challenge is handling the full permission lifecycle: requesting, receiving, handling denial, and requesting again when appropriate, while still providing a useful experience when sensors are unavailable, such as on desktop browsers without GPS hardware, or when the user declines. Progressive enhancement is the guiding principle: the feature works without the sensor, and the sensor makes it better. A location-aware store finder that falls back to a postcode input field when permission is denied is more useful than one that renders an empty state.

Consider a delivery tracking feature where a courier's position updates on a map as they move. An initial implementation might ask for a position once on load with getCurrentPosition. Real-time tracking of the courier's path needs watchPosition instead, which installs a callback that fires each time the device's location changes beyond a configurable accuracy threshold.

Visual ​

Example ​

js
function getUserLocation() {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(new Error('Geolocation not supported'));
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (pos) => resolve({
        lat: pos.coords.latitude,
        lng: pos.coords.longitude,
      }),
      (err) => {
        const messages = {
          1: 'Permission denied, enable location in browser settings',
          2: 'Position unavailable, no location fix',
          3: 'Timeout, location request took too long',
        };
        reject(new Error(messages[err.code] ?? 'Unknown error'));
      },
      { enableHighAccuracy: false, timeout: 8000, maximumAge: 60000 }
    );
  });
}

Best Practices ​

MUST request Geolocation permission only after explaining to the user why location data is needed. Permission prompts that appear without context are dismissed at high rates, and in many browsers a single dismissal permanently blocks further prompts for that origin. Show a brief, inline explanation next to the button that will trigger the request, before calling getCurrentPosition. Informed consent carries legal weight beyond UX: many data protection regimes, including the EU's GDPR, require a lawful basis before an application may collect location data, for which explicit user consent is the mechanism browsers surface.

SHOULD specify a timeout value in getCurrentPosition and watchPosition options to prevent indefinite loading states. Without one, the browser may wait for GPS hardware indefinitely: a cold start can take over 30 seconds and occasionally fails to acquire a fix at all in poor signal conditions. A timeout of 5-10 seconds, paired with a TIMEOUT error handler that falls back to a less accurate method or a manual input form, keeps the wait bounded and predictable.

MUST call clearWatch on the return value of watchPosition when continuous tracking is no longer needed. watchPosition keeps querying location hardware until explicitly stopped, which drains battery even after the feature requiring live location is no longer visible. Store the watch ID in a variable the cleanup code can reach, and call navigator.geolocation.clearWatch(watchId) on component unmount, route change, or feature deactivation. In React, the canonical pattern is to return the clearWatch call from useEffect.

MUST handle all three GeolocationPositionError codes: PERMISSION_DENIED (1), POSITION_UNAVAILABLE (2), and TIMEOUT (3). Each code needs a distinct response. Code 1 needs instructions for enabling location in browser or OS settings. Code 2 needs a fallback input method, such as a postcode field, because the device cannot determine its position regardless of permission state. Code 3 needs a retry option or a less accurate fallback, since the fix timed out but a later attempt may succeed. The err.message property is not standardized across browsers and must not be used as the primary error text shown to users.

SHOULD check for DeviceOrientationEvent.requestPermission before attaching orientation or motion listeners on iOS. On iOS 13 and later, motion events are gated behind an explicit permission call that must originate from a user gesture. Attaching listeners without calling requestPermission first produces no errors and no events on iOS, which makes the failure invisible without testing on an actual device. Check typeof DeviceOrientationEvent.requestPermission === 'function'; where it exists, call it and await the result before adding the listener, and where it does not exist, attach the listener directly.

MUST serve any page that uses these APIs over HTTPS or from localhost. The Geolocation, Device Orientation, and Device Motion APIs are all restricted to secure contexts. A plain HTTP page cannot access any of them regardless of the user's permission state: the browser refuses the API outright and never shows a permission prompt. A staging environment served over HTTP will show these APIs as silently unavailable, which can hide bugs until the production deployment. Check window.isSecureContext at startup and surface an explicit error rather than letting the API call fail silently.

Design Thinking ​

One-time vs. continuous position ​

getCurrentPosition retrieves a single position fix and calls the success callback once; it fits features that need location at a specific moment, such as finding nearby places or populating a shipping address field. watchPosition installs a continuous listener that fires the callback every time the position changes beyond a threshold, and it returns a numeric watch ID for later cleanup.

A one-time fix has no cleanup step. A watch does: it must be paired with navigator.geolocation.clearWatch(watchId) once the feature that needs live location is no longer visible, whether because the user navigated away or the component unmounted. Leaving watchPosition active past that point keeps GPS hardware polling in the background, which is one of the fastest ways to drain a mobile device's battery.

The PositionOptions triangle ​

getCurrentPosition and watchPosition both accept a PositionOptions object as a third argument, and its three properties trade against each other. Raising enableHighAccuracy to request a GPS fix usually means raising timeout too, since GPS needs time to lock onto satellites: a cold start can take 30-60 seconds, versus a near-instant Wi-Fi or cell-based fix. Shortening maximumAge forces more frequent hardware queries, which suits a turn-by-turn navigation feature that must reflect the latest position, but wastes battery on a feature that only needs to know which city the user is in.

The right calibration depends on what the feature needs, not on maximizing accuracy by default. A store finder or weather widget can leave enableHighAccuracy false and accept a maximumAge of a minute or more; a navigation or sports-tracking feature needs enableHighAccuracy: true and a short maximumAge, and should show a loading indicator with a cancel option while GPS acquires its first fix, since that wait can feel long to the user.

Deep Dive ​

PositionOptions field reference ​

enableHighAccuracy requests a GPS fix when possible rather than relying on Wi-Fi triangulation or cell tower data; it defaults to false. GPS under open sky typically resolves to single-digit-metre horizontal accuracy, about 4.9 metres for a typical smartphone GNSS receiver, while network-based positioning is coarser, commonly tens to hundreds of metres depending on the density of nearby Wi-Fi access points and cell towers.

timeout sets the maximum milliseconds the browser may spend acquiring a position before the error callback fires with code TIMEOUT (3); it has no default. maximumAge sets the maximum acceptable age, in milliseconds, of a cached position: if the device already holds a fix no older than maximumAge, the browser returns it immediately without querying hardware. Sensible defaults for most applications are { enableHighAccuracy: false, timeout: 8000, maximumAge: 60000 }.

DeviceOrientationEvent and DeviceMotionEvent fields ​

DeviceOrientationEvent fires continuously as the device's spatial orientation changes, exposing three Euler angles. alpha is rotation around the Z axis, 0-360 degrees, equivalent to compass heading when absolute is true. beta is front-to-back tilt, -180 to 180 degrees: it is 0 when the device lies flat, and rises toward 90 as the top tips forward, which is roughly the beta value when someone holds a phone upright in portrait mode to read it. gamma is left-to-right tilt, -90 to 90 degrees: it stays near 0 whether the device is lying flat or held upright in portrait, as long as it is not leaning sideways, and moves toward ±90 as the device is rolled onto its left or right edge. Use cases include AR overlay alignment, compass UI components that rotate to face north, and tilt-to-scroll interfaces.

DeviceMotionEvent reports raw sensor data rather than computed orientation. acceleration gives X, Y, and Z acceleration excluding gravity; accelerationIncludingGravity includes the gravitational vector; and rotationRate gives alpha, beta, and gamma rotation rates in degrees per second. These are useful for step counting and shake detection, where the raw sensor stream is more informative than the filtered orientation angles. Both events are rate-limited by the browser, typically around 16ms (roughly 60Hz), though this varies by device.

iOS 13 and later requires the explicit DeviceOrientationEvent.requestPermission() call described in Best Practices before either event fires. Android and desktop browsers grant motion events without a separate permission step.

Secure context requirement ​

The Geolocation, Device Orientation, and Device Motion APIs are each restricted to pages served over HTTPS or from localhost. This restriction is enforced at the browser level and cannot be bypassed in JavaScript. window.isSecureContext reports whether the current page qualifies, and checking it at startup lets the application show a clear error instead of a silently failing API call.

Pausing watchPosition with the Page Visibility API ​

Pair watchPosition with the Page Visibility API's visibilitychange event to reduce background battery use further. Call clearWatch when document.hidden becomes true, then call watchPosition again when the tab returns to the foreground. This keeps GPS hardware from polling for a tab the user cannot currently see, on top of the baseline rule of calling clearWatch once the feature itself becomes inactive.

Progressive enhancement in practice ​

The code path that calls getCurrentPosition or registers a deviceorientation listener should always be preceded by a feature-detection check ('geolocation' in navigator, 'DeviceOrientationEvent' in window) and paired with an error handler that activates a fallback UI. Three failure states need a fallback: the API is absent on the device, the permission was denied, or the sensor is temporarily unavailable. A store finder can fall back to a manual search field; a navigation feature can fall back to a manual address entry form. No state should leave the user on a blank screen or a loading indicator with no way out.

Permission decisions persist across sessions: once a user grants or denies geolocation access, most browsers remember that decision for the origin and do not re-prompt. navigator.permissions.query({ name: 'geolocation' }) (FEE-415) reads the current permission state before calling getCurrentPosition, so the application can route straight to the fallback UI instead of waiting for the error callback. The PermissionStatus object this returns also fires an onchange event. This lets a watchPosition consumer detect a mid-session revocation, for instance if the user opens browser settings in another tab and turns the permission off, and switch to the fallback UI without waiting for the next failed GPS callback.

Accuracy, Sources, and Privacy of Position Data ​

The position returned by getCurrentPosition may come from GPS satellites, Wi-Fi access point triangulation, cell tower data, or a combination of the three, depending on what signals are available to the device. GeolocationCoordinates.accuracy reports the estimated horizontal accuracy in metres, and per the W3C Geolocation specification this is a 95%-confidence radius: a value of 5 means the browser has 95% confidence that the true position lies within 5 metres of the reported coordinates. Applications that display the position on a map should render this as an uncertainty circle rather than a single pin, so the user can see how precise the reported location actually is.

enableHighAccuracy: true only helps on hardware that can produce a better fix. A laptop or desktop without a GPS receiver will not improve its accuracy regardless of the setting, and coords.accuracy on such devices typically stays in the hundreds of metres.

coords.altitude and coords.altitudeAccuracy may be null on devices that do not report altitude: most mobile devices with a GNSS receiver report it, but network-based positioning sources typically do not. coords.heading and coords.speed are null under the same conditions, or when the device is stationary. Always null-check these four properties before use.

Geolocation data is sensitive. A precise coordinate pair, tracked over time, can reveal where someone lives, works, or receives medical care. Design for data minimization: request only the accuracy the feature needs, hold coordinates only for as long as the feature is active, and do not persist raw coordinates in localStorage or sessionStorage. If coordinates must reach a backend, truncate them to the precision the feature actually needs rather than forwarding the sensor's full precision; a feature that only needs neighborhood-level location does not need six decimal places of latitude and longitude. Front-end code MUST NOT log raw coordinates into application logs or third-party error-tracking and analytics services: those are typically outside the organization's data-processing agreements, and location data, once ingested by a third party, is difficult to have deleted.

References ​