How to use the HTML5 Geolocation API
· Category: HTML & CSS
Short answer
The Geolocation API exposes navigator.geolocation, which provides methods like getCurrentPosition and watchPosition to retrieve latitude and longitude coordinates.
Steps
- Check that
navigator.geolocationexists. - Call
getCurrentPosition(success, error, options). - Read
coords.latitudeandcoords.longitudefrom the success callback. - Handle errors such as permission denial or timeout gracefully.
Example
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position.coords.latitude, position.coords.longitude);
},
(error) => {
console.error('Error:', error.message);
},
{ enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }
);
}
Tips
- Always request location in response to a user gesture.
- Explain why you need location before prompting to increase acceptance rates.
- Use HTTPS; geolocation is blocked on many browsers over insecure connections.
- Respect user privacy and provide value immediately after obtaining location data.