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

  1. Check that navigator.geolocation exists.
  2. Call getCurrentPosition(success, error, options).
  3. Read coords.latitude and coords.longitude from the success callback.
  4. 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.