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:
HTTPS: Geolocation only works on secure origins (https:// or localhost)
User Permission: Users must explicitly grant permission to access their location
User Gesture: Initial requests should be triggered by user interaction
Always handle permission denials gracefully and provide clear explanations of why your app needs location access.
Usage
Basic Location Request
Continuous Location Tracking
Distance Calculator
Location-Based Content
Geofencing
Fitness Tracker with Route Recording
Store Locator
Parameters
None
Actions
locate
locateRetrieves 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): Iftrue, requests the most accurate location available (may use GPS). Default:falsetimeout(number, optional): Maximum time (in milliseconds) to wait for a position. Default:InfinitymaximumAge(number, optional): Maximum age (in milliseconds) of a cached position that is acceptable to return. Default:0
enableHighAccuracy: true provides better accuracy but uses more battery and may take longer. Use it only when precision is important.
watch
watchStarts 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): Iftrue, requests high-accuracy position updates. Default:falsetimeout(number, optional): Maximum time to wait for each position update. Default:InfinitymaximumAge(number, optional): Maximum age of cached positions. Default:0
Continuous tracking consumes significant battery power. Always provide a way to stop tracking when it's no longer needed.
clearWatch
clearWatchStops continuous position tracking that was started with the watch action.
Targets
None
Events
pwa--geolocation:position
pwa--geolocation:positionDispatched when a position update is received (from either locate or watch actions).
Payload: {coords, timestamp}
coords.latitude(number): Latitude in decimal degreescoords.longitude(number): Longitude in decimal degreescoords.accuracy(number): Accuracy of the position in meterscoords.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
pwa--geolocation:errorDispatched 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
pwa--geolocation:unsupportedDispatched when the browser does not support the Geolocation API.
No payload
Example:
pwa--geolocation:watch:cleared
pwa--geolocation:watch:clearedDispatched when continuous position tracking is stopped (via clearWatch action).
No payload
Example:
Best Practices
Request permission contextually: Ask for location access when the user interacts with a location-based feature
Explain why you need it: Clearly communicate why your app needs location access
Handle errors gracefully: Provide fallback options when location access is denied or unavailable
Use appropriate accuracy: Don't request high accuracy unless you really need it
Stop tracking when done: Always clear watches to save battery
Cache positions wisely: Use
maximumAgeto avoid unnecessary GPS usageRespect privacy: Don't share or store location data without explicit consent
Provide visual feedback: Show loading states while waiting for position
Set reasonable timeouts: Don't let requests hang indefinitely
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:
Indoor location requests (GPS signal blocked)
enableHighAccuracyset tofalseDevice limitations
Solutions:
Use
enableHighAccuracy: truefor better precisionRequest 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
watchonly when necessaryAlways call
clearWatchwhen doneSet reasonable
timeoutvaluesUse
enableHighAccuracy: falsewhen precision isn't criticalConsider updating less frequently
HTTPS requirement
Geolocation only works on secure contexts (HTTPS or localhost). If testing on a local network, use:
localhostinstead of127.0.0.1Set up HTTPS for local development
Use tools like ngrok for testing on mobile devices
Last updated
Was this helpful?