Geolocation

The Geolocation component provides an interface to the Geolocation API, enabling your Progressive Web App to access the user's geographic location. This allows you to create location-aware applications that can provide personalized content, navigation, and services based on the user's position.

This component is particularly useful for:

  • Location-based services and recommendations

  • Mapping and navigation applications

  • Delivery and transportation tracking

  • Fitness and activity tracking apps

  • Store locators and proximity searches

  • Emergency services and safety features

  • Weather and local information services

  • Social check-ins and location sharing

Browser Support

The Geolocation API is widely supported across all modern browsers on both desktop and mobile devices. However, for security and privacy reasons, browsers require:

  1. HTTPS: Geolocation only works on secure origins (https:// or localhost)

  2. User Permission: Users must explicitly grant permission to access their location

  3. User Gesture: Initial requests should be triggered by user interaction

circle-exclamation

Usage

Basic Location Request

Continuous Location Tracking

Distance Calculator

Location-Based Content

Geofencing

Fitness Tracker with Route Recording

Store Locator

Parameters

None

Actions

locate

Retrieves the user's current position once. This is ideal for one-time location requests like "find stores near me" or "show local weather".

Options:

  • enableHighAccuracy (boolean, optional): If true, requests the most accurate location available (may use GPS). Default: false

  • timeout (number, optional): Maximum time (in milliseconds) to wait for a position. Default: Infinity

  • maximumAge (number, optional): Maximum age (in milliseconds) of a cached position that is acceptable to return. Default: 0

circle-info

enableHighAccuracy: true provides better accuracy but uses more battery and may take longer. Use it only when precision is important.

watch

Starts continuous position tracking. The component will repeatedly update the position as the user moves. This is ideal for navigation, fitness tracking, or real-time location sharing.

Options:

  • enableHighAccuracy (boolean, optional): If true, requests high-accuracy position updates. Default: false

  • timeout (number, optional): Maximum time to wait for each position update. Default: Infinity

  • maximumAge (number, optional): Maximum age of cached positions. Default: 0

circle-exclamation

clearWatch

Stops continuous position tracking that was started with the watch action.

Targets

None

Events

pwa--geolocation:position

Dispatched when a position update is received (from either locate or watch actions).

Payload: {coords, timestamp}

  • coords.latitude (number): Latitude in decimal degrees

  • coords.longitude (number): Longitude in decimal degrees

  • coords.accuracy (number): Accuracy of the position in meters

  • coords.altitude (number|null): Altitude in meters above sea level (if available)

  • coords.altitudeAccuracy (number|null): Accuracy of altitude in meters (if available)

  • coords.heading (number|null): Direction of travel in degrees (0-360) (if available)

  • coords.speed (number|null): Speed in meters per second (if available)

  • timestamp (number): Timestamp when the position was acquired

Example:

pwa--geolocation:error

Dispatched when an error occurs while retrieving the position (permission denied, timeout, position unavailable).

Payload: Error object with code and message

  • code (number): Error code (1: PERMISSION_DENIED, 2: POSITION_UNAVAILABLE, 3: TIMEOUT)

  • message (string): Human-readable error description

Example:

pwa--geolocation:unsupported

Dispatched when the browser does not support the Geolocation API.

No payload

Example:

pwa--geolocation:watch:cleared

Dispatched when continuous position tracking is stopped (via clearWatch action).

No payload

Example:

Best Practices

  1. Request permission contextually: Ask for location access when the user interacts with a location-based feature

  2. Explain why you need it: Clearly communicate why your app needs location access

  3. Handle errors gracefully: Provide fallback options when location access is denied or unavailable

  4. Use appropriate accuracy: Don't request high accuracy unless you really need it

  5. Stop tracking when done: Always clear watches to save battery

  6. Cache positions wisely: Use maximumAge to avoid unnecessary GPS usage

  7. Respect privacy: Don't share or store location data without explicit consent

  8. Provide visual feedback: Show loading states while waiting for position

  9. Set reasonable timeouts: Don't let requests hang indefinitely

  10. Test offline behavior: Ensure your app handles lack of GPS signal gracefully

Coordinate Calculations

Distance Between Two Points (Haversine Formula)

Check if Point is Within Radius

Convert Coordinates to Compass Direction

Error Handling

Complete Example: Real-Time Delivery Tracker

Troubleshooting

Location access denied

Solution: Provide clear instructions on how to enable location permissions in browser settings. Consider showing a help modal with browser-specific instructions.

Low accuracy

Common causes:

  1. Indoor location requests (GPS signal blocked)

  2. enableHighAccuracy set to false

  3. Device limitations

Solutions:

  • Use enableHighAccuracy: true for better precision

  • Request location outdoors when possible

  • Display accuracy information to users

Timeout errors

Solutions:

  • Increase timeout value: timeout: 15000 (15 seconds)

  • Show loading state to users

  • Provide retry option

  • Consider using cached positions with maximumAge

Battery drain

Solutions:

  • Use watch only when necessary

  • Always call clearWatch when done

  • Set reasonable timeout values

  • Use enableHighAccuracy: false when precision isn't critical

  • Consider updating less frequently

HTTPS requirement

Geolocation only works on secure contexts (HTTPS or localhost). If testing on a local network, use:

  • localhost instead of 127.0.0.1

  • Set up HTTPS for local development

  • Use tools like ngrok for testing on mobile devices

Last updated

Was this helpful?