Geolocation in HTML5 allows web applications to access a user’s geographical location. This can be incredibly useful for services like mapping, local recommendations, and more.
Approach
-
Verify if the user’s browser supports geolocation using
navigator.geolocation
. -
Use
navigator.geolocation.getCurrentPosition()
to get the user’s current latitude and longitude. - Implement callbacks for success and failure to manage location data or handle errors.
- Provide optional settings like accuracy, timeout, and maximum age using an options object.
- Utilize obtained location data in your application, such as displaying it on a map or customizing content.
Example:
HTML
<!DOCTYPE html> < html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content =
"width=device-width, initial-scale=1.0" >
< title >Geolocation in HTML5</ title >
</ head >
< body >
< h1 >GeeksforGeeks Geolocation</ h1 >
< script >
// Check if the browser supports geolocation
if ("geolocation" in navigator) {
// Get the user's current position
navigator.geolocation.getCurrentPosition(
function (position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
document.body.innerHTML +=
"< p >Latitude: " + latitude + "</ p >";
document.body.innerHTML +=
"< p >Longitude: " + longitude + "</ p >";
},
function (error) {
console.error("Error getting location: " + error.message);
}
);
} else {
alert("Geolocation is not supported by your browser");
}
</ script >
</ body >
</ html >
|
Output:
Article Tags :