HTML5 Geolocation
The HTML5 Geolocation API allows web applications to obtain the geographic location information of the user's device with user consent. This enables the development of Location-Based Services (LBS), such as:
- Marking the user's current location on a map
- Providing localized search results
- "Nearby people" functionality
Privacy Note: Geolocation is a feature that involves user privacy. Therefore, the browser must pop up a window requesting explicit user authorization before any attempt to obtain user location information.
Getting the Current Position
The core method for getting user location is navigator.geolocation.getCurrentPosition().
This method asynchronously attempts to obtain the device's position and accepts three parameters:
successCallback: The callback function called when location is successfully obtained. This function receives aPositionobject as a parameter containing location information.errorCallback(optional): The callback function called when location retrieval fails. This function receives aPositionErrorobject.options(optional): A configuration object for setting location retrieval parameters like accuracy, timeout, etc.
Example Code
The Position Object
When location is successfully obtained, successCallback receives a Position object whose coords property contains key location data:
position.coords.latitude: Latitude (decimal degrees)position.coords.longitude: Longitude (decimal degrees)position.coords.accuracy: Position accuracy (meters)position.coords.altitude: Altitude (meters, if available)position.coords.speed: Speed (meters/second, if available)position.coords.heading: Direction (degrees, if available)
The PositionError Object
When location retrieval fails, errorCallback receives a PositionError object whose code property helps determine the reason for failure:
1:PERMISSION_DENIED- User denied authorization.2:POSITION_UNAVAILABLE- Cannot obtain current position (e.g., network issues or can't connect to GPS satellites).3:TIMEOUT- Request timed out.
Displaying Position on a Map
After obtaining latitude and longitude, the most common application is to display it on a map. You can use various map service providers' APIs (like Google Maps, OpenStreetMap, etc.) to achieve this.
Here's a simple example link using Google Maps: