HTML Geolocation API

HTML Geolocation API

The Geolocation API allows a web page to access the geographical location of a user’s device (with their permission). You can use it to get the latitude, longitude, altitude, and more for location-based services.

This API is available in modern browsers and is usually used with JavaScript, not just HTML.


Key Features

  • Get current position of the user.

  • Track real-time location changes.

  • Works with GPS, Wi-Fi, or IP address depending on the device.

  • Requires user permission for privacy.


Methods

  1. navigator.geolocation.getCurrentPosition(success, error)

    • Retrieves the user’s current position once.

  2. navigator.geolocation.watchPosition(success, error)

    • Continuously tracks location changes.

  3. navigator.geolocation.clearWatch(id)

    • Stops tracking location started by watchPosition.


Example: Get User Location


 


Explanation

  • navigator.geolocation.getCurrentPosition() → Requests the current location.

  • position.coords.latitude and position.coords.longitude → Get latitude and longitude.

  • showError() → Handles cases when the user denies access or location is unavailable.


Key Points

  • User permission is required for privacy.

  • Location may not be 100% accurate on all devices.

  • Can be combined with Google Maps API to show location visually.

  • Works on desktop and mobile devices.


The Geolocation API is useful for:

  • Location-based services (maps, weather apps)

  • Finding nearby stores or services

  • Tracking user location in real-time apps

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *