Web Geolocation API: Locating the User's Position
The HTML Geolocation API allows you to determine the geographical position of a user. Due to privacy concerns, this information is only available if the user grants permission.
Note: Geolocation is most accurate on devices with GPS, such as smartphones.
Browser Support
The Geolocation API is supported in all major browsers:
- Chrome: Yes
- Firefox: Yes
- Internet Explorer: Yes
- Safari: Yes
- Opera: Yes
Important: The Geolocation API functions only in secure contexts (HTTPS). If your site uses HTTP, requests to access the user's location will fail.
Using the Geolocation API
The getCurrentPosition() method is used to retrieve the user's position. Below is an example that returns the user's latitude and longitude:
<!DOCTYPE html><html><head> <title>Geolocation API Example</title></head><body>
<p id="demo">Click the button to get your coordinates:</p><button onclick="getLocation()">Try It</button><script>const x = document.getElementById("demo");function getLocation(
) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError); } else { x.innerHTML = "Geolocation is not supported by this browser."; }}
function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;}function showError(error) { switch(error.code) { case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."; 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></body></html>
Handling Errors and Rejections
The second parameter of the getCurrentPosition() method handles errors. It specifies a function to execute if the user's location cannot be obtained:
function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML = "User denied the request for Geolocation."; 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; }}
Displaying the Result on a Map
To display the location on a map, use a map service like Google Maps. The following example uses a static image to show the location:
function showPosition(position) { let latlon = position.coords.latitude + "," + position.coords.longitude; let img_url = "https://maps.googleapis.com/maps/api/staticmap?center=" + latlon + "&zoom=14&size=400x300&sensor=false&key=YOUR_KEY"; document.getElementById("mapholder").innerHTML = "<img src='" + img_url + "'>";}
Geolocation Object: Other Methods
The Geolocation object has additional methods:
- watchPosition(): Continuously updates and returns the user's current position as they move.
- clearWatch(): Stops the watchPosition() method.
The following example demonstrates the watchPosition() method, which requires a device with an accurate GPS (such as a smartphone):
<!DOCTYPE html><html><head> <title>Geolocation API Example</title></head><body><p id="demo">Click the button to watch your coordin
ates:</p><button onclick="startWatching()">Start Watching</button><script>const x = document.getElementById("demo");function startWatching() { if (navigator.geolocation) { navigator.geolocation.watchPosition(showPosition, showError);
} else { x.innerHTML = "Geolocation is not supported by this browser."; }}
function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;}</script></body></html>
This page demonstrates how to show a user's position on a map using the Geolocation API. Geolocation is also useful for providing location-specific information, such as up-to-date local information, points of interest nearby, and GPS-based turn-by-turn navigation.
Data Returned by getCurrentPosition()
The getCurrentPosition() method returns an object with the following properties:
- coords.latitude: The latitude as a decimal number (always returned).
- coords.longitude: The longitude as a decimal number (always returned).
- coords.accuracy: The accuracy of the position (always returned).
- coords.altitude: The altitude in meters above mean sea level (if available).
- coords.altitudeAccuracy: The altitude accuracy of the position (if available).
- coords.heading: The heading in degrees clockwise from North (if available).
- coords.speed: The speed in meters per second (if available).
- timestamp: The date/time of the response (if available).