Loading lessons...
HTML Geolocation
HTML Geolocation
The Geolocation API asks the browser where you are. It powers maps, weather apps, and "find stores near me"!
What is it?
The Geolocation API is a JavaScript tool that finds the user's position. It's not an HTML tag: it's JavaScript that works with HTML.
How it works
navigator.geolocation.getCurrentPosition(showPosition);
When the browser knows the position, it calls showPosition:
function showPosition(position) {
document.getElementById("demo").innerHTML =
"Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
Wait, you MUST ask first!
The browser always asks the user for permission. If they say no, you don't get the location. That's privacy protection, and it's very important.
Position errors
The user might say no, or the location might not be found. Handle it gracefully:
navigator.geolocation.getCurrentPosition(showPosition, showError);
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
}
}
Other things you can do
watchPosition(): keep watching and update as the user moves.clearWatch(): stop watching.- You can check accuracy, speed, altitude, and more.
A practical example (map)
Combine the position with a map API to show where you are:
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
// Then use lat/lon to show a map centered on the user!
}
TL;DR
- Geolocation API finds the user's location with JavaScript.
getCurrentPosition()gets it once;watchPosition()keeps tracking.- The browser ALWAYS asks for permission first.
- Handle errors (denied, unavailable, timeout) politely.
- Use it to build maps, weather, and "near me" features.