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
<button onclick="getLocation()">Get My Location</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
// Check if the browser supports geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Your browser does not support geolocation.";
}
}
// Callback function for successful location retrieval
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
// Callback function for failed location retrieval
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the geolocation request."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>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:
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var mapUrl = `https://maps.google.com/maps?q=${lat},${lon}`;
window.open(mapUrl, '_blank');
}