Geolocation API
Access user location data with the HTML5 Geolocation API. Build location-aware applications with position tracking, mapping integration, and location-based services.
How do you get the user's location in JavaScript?
Call navigator.geolocation.getCurrentPosition(success, error). The browser asks the user for permission, then calls success with a position containing coords.latitude, coords.longitude and coords.accuracy. Use watchPosition() for continuous updates. Geolocation only works on HTTPS pages.
navigator.geolocation.getCurrentPosition(
(pos) => console.log(pos.coords.latitude, pos.coords.longitude),
(err) => console.warn(err.message),
{ enableHighAccuracy: true, timeout: 10000 }
);Geolocation Fundamentals
getCurrentPosition()
Get the user's current location once
watchPosition()
Continuously track position changes
clearWatch()
Stop position tracking and cleanup
Interactive Geolocation Examples
Explore location services including current position, position tracking, and customizable options for accuracy and timing.
Geolocation API Methods & Properties
getCurrentPosition()
Method Signature
navigator.geolocation.getCurrentPosition(success, error, options)- success: Callback for successful location
- error: Callback for errors
- options: Configuration object
Position Object Properties
coords.latitude- Decimal degreescoords.longitude- Decimal degreescoords.accuracy- Meterscoords.altitude- Meters above sea levelcoords.heading- Degrees from northcoords.speed- Meters per secondtimestamp- Time of measurement
watchPosition()
Continuous Tracking
- • Returns watch ID for later clearing
- • Fires callback on position changes
- • Configurable update frequency
- • Automatic error handling
- • Battery usage considerations
Best Practices
- • Clear watch when not needed
- • Handle permission changes
- • Throttle position updates
- • Monitor battery usage
- • Provide user controls
Position Options Configuration
enableHighAccuracy
Request GPS for better precision
- true: GPS preferred
- false: Network location
- • Higher battery usage
- • Better accuracy
timeout
Maximum time to get position (ms)
- • Default: Infinity
- • Recommended: 5000-15000
- • Triggers error on timeout
- • User experience balance
maximumAge
Accept cached position age (ms)
- • Default: 0 (no cache)
- • Infinity: any cached
- • Performance optimization
- • Balance freshness vs speed
Error Handling & Troubleshooting
Error Codes
- PERMISSION_DENIED (1):
User denied geolocation request - POSITION_UNAVAILABLE (2):
Location information unavailable - TIMEOUT (3):
Request timed out
Common Issues
- • HTTPS requirement on some browsers
- • Permission popup blocking
- • GPS not available indoors
- • Network connectivity issues
- • Privacy settings blocking location
Error Recovery Strategies
- • Graceful degradation to IP location
- • Manual location input fallback
- • Retry with different options
- • Cache last known position
- • Inform user about requirements
User Communication
- • Clear permission request explanation
- • Loading indicators during requests
- • Helpful error messages
- • Alternative action suggestions
- • Privacy reassurance
Real-World Applications & Use Cases
E-Commerce & Retail
- • Store locator with directions
- • Local inventory availability
- • Delivery time estimation
- • Regional pricing and offers
- • Pickup location suggestions
Transportation & Logistics
- • Real-time vehicle tracking
- • Route optimization
- • Ride-sharing applications
- • Delivery tracking
- • Fleet management
Social & Content
- • Location-based social networks
- • Geotagged content creation
- • Local event discovery
- • Check-in functionality
- • Nearby user connections
Weather & Environment
- • Localized weather forecasts
- • Air quality monitoring
- • Emergency alerts
- • Environmental data collection
- • Outdoor activity recommendations
Performance Optimization & Best Practices
Battery Optimization
- • Use appropriate accuracy settings
- • Clear watchers when not needed
- • Implement intelligent update intervals
- • Consider device movement patterns
- • Provide user control over tracking
Data Usage Optimization
- • Cache location data appropriately
- • Reduce API call frequency
- • Use significant change detection
- • Implement offline capabilities
- • Compress location data transmission
Implementation Checklist
- ✓ Feature detection before use
- ✓ HTTPS for secure contexts
- ✓ Clear permission requests
- ✓ Comprehensive error handling
- ✓ Fallback mechanisms
- ✓ Performance monitoring
- ✓ User privacy controls
- ✓ Cross-browser testing
- ✓ Mobile device optimization
- ✓ Accessibility considerations
Code Editor
<button id="find">Where am I?</button>
<p id="out"></p>Preview
Privacy & Security Considerations
User Permissions
- Always requires explicit user consent
- Users can deny or revoke permissions
- Explain why location is needed
Best Practices
- Use HTTPS for secure transmission
- Set appropriate timeouts
- Handle all error cases gracefully
Geolocation API — step by step
Request the user's location
Call navigator.geolocation.getCurrentPosition(successCallback, errorCallback) to request the current position. The browser will prompt the user for permission before providing coordinates.
🎯 Quick Check
Which method do you use to continuously track a user's location changes?
HTML Geolocation API: summary
Key points
- Ask for location in response to a user action, such as a "Find stores near me" button, not on page load.
- Always handle the error callback: users can deny permission, or the location may be unavailable.
enableHighAccuracyuses GPS on phones, which is slower and uses more battery.
Frequently asked questions
›Why is geolocation not working?
Usually the page isn't served over HTTPS, the user or browser denied permission, or the request timed out. Check the error callback's code and message.