The HTML5 geolocation feature enables you to discover the geographic coordinates (latitude and longitude) of your website's visitor's current location.
This functionality enhances the browsing experience by allowing you to provide search results that are close to the user's physical location.
Obtaining a site visitor's position using the HTML5 geolocation API is straightforward. It utilizes three methods within the navigator.geolocation
object: getCurrentPosition()
, watchPosition()
, and clearWatch()
.
The following example demonstrates geolocation by displaying the current position. However, the user needs to grant permission for the browser to share their position with the web server.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Current Position</title>
<script>
function showPosition() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
document.getElementById("result").innerHTML = positionInfo;
});
} else {
alert("Sorry, your browser does not support HTML5 geolocation.");
}
}
</script>
</head>
<body>
<div id="result">
<!--Position information will be inserted here-->
</div>
<button type="button" onclick="showPosition();">Show Position</button>
</body>
</html>
Note: Web browsers require explicit permission from users to share their location with a webpage. The geolocation standard mandates obtaining user consent for websites requesting location data.
Situations may arise where a user opts not to share their location data. To address such scenarios, you can specify two functions when invoking the getCurrentLocation()
function.
The first function executes if your geolocation attempt succeeds, while the second handles failures. Let's explore an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Handling Geolocation Errors</title>
<script>
// Define global variable
var result;
function showPosition() {
// Store the element where the result will be displayed
result = document.getElementById("result");
// If geolocation is available, attempt to retrieve the visitor's position
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
result.innerHTML = "Getting position information...";
} else {
alert("Sorry, your browser does not support HTML5 geolocation.");
}
};
// Define callback function for successful attempt
function successCallback(position) {
result.innerHTML = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
}
// Define callback function for failed attempt
function errorCallback(error) {
if(error.code == 1) {
result.innerHTML = "You've chosen not to share your position, and that's okay. We won't ask again.";
} else if(error.code == 2) {
result.innerHTML = "The network is down or the positioning service cannot be reached.";
} else if(error.code == 3) {
result.innerHTML = "The attempt timed out before obtaining location data.";
} else {
result.innerHTML = "Geolocation failed due to an unknown error.";
}
}
</script>
</head>
<body>
<div id="result">
<!--Position information will be inserted here-->
</div>
<button type="button" onclick="showPosition();">Show Position</button>
</body>
</html>
Geolocation data opens up exciting possibilities, such as displaying the user's location on a Google Map. The example below demonstrates how to show your current location on a Google Map using latitude and longitude data obtained through the HTML5 geolocation feature.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Using the Google Maps</title>
<script>
function showPosition() {
navigator.geolocation.getCurrentPosition(showMap);
}
function showMap(position) {
// Get location data
var latlong = position.coords.latitude + "," + position.coords.longitude;
// Set Google map source url
var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center="+latlong+"&zoom=16&size=400x300&output=embed";
// Create and insert Google map
document.getElementById("embedMap").innerHTML = "<img alt='Map Holder' src='"+ mapLink +"'>";
}
</script>
</head>
<body>
<button type="button" onclick="showPosition();">Show My Position on Google Map</button>
<div id="embedMap">
<!--Google map will be embedded here-->
</div>
</body>
</html>
While the previous example displays the location on a Google Map using a static image, you can create interactive Google Maps with features like dragging, zooming in/out, and more, akin to real-life experiences. Let's explore the following example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Using the Google Maps</title>
<script src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function showPosition() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showMap, showError);
} else {
alert("Sorry, your browser does not support HTML5 geolocation.");
}
}
// Define callback function for successful attempt
function showMap(position) {
// Get location data
lat = position.coords.latitude;
long = position.coords.longitude;
var latlong = new google.maps.LatLng(lat, long);
var myOptions = {
center: latlong,
zoom: 16,
mapTypeControl: true,
navigationControlOptions: {
style:google.maps.NavigationControlStyle.SMALL
}
}
var map = new google.maps.Map(document.getElementById("embedMap"), myOptions);
var marker = new google.maps.Marker({ position:latlong, map:map, title:"You are here!" });
}
// Define callback function for failed attempt
function showError(error) {
if(error.code == 1) {
result.innerHTML = "You've decided not to share your position, but it's OK. We won't ask you again.";
} else if(error.code == 2) {
result.innerHTML = "The network is down or the positioning service can't be reached.";
} else if(error.code == 3) {
result.innerHTML = "The attempt timed out before it could get the location data.";
} else {
result.innerHTML = "Geolocation failed due to unknown error.";
}
}
</script>
</head>
<body>
<button type="button" onclick="showPosition();">Show My Position on Google Map</button>
<div id="embedMap" style="width: 400px; height: 300px;">
<!--Google map will be embedded here-->
</div>
</body>
</html>
If you're keen to explore further functionalities of the Google Maps Javascript API, you can visit this URL.
While our previous examples have all relied on the getCurrentPosition()
method, the geolocation object also boasts another method called watchPosition()
. This function allows you to track the movement of visitors by continually updating the position as it changes.
Similar to getCurrentPosition()
, watchPosition()
accepts the same input parameters. However, it might invoke the success function multiple times: initially when it retrieves the location and subsequently whenever a new position is detected. Let's see how it operates:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Watching Position</title>
<script>
// Set global variable
var watchID;
function showPosition() {
if(navigator.geolocation) {
watchID = navigator.geolocation.watchPosition(successCallback);
} else {
alert("Sorry, your browser does not support HTML5 geolocation.");
}
}
function successCallback(position) {
toggleWatchBtn.innerHTML = "Stop Watching";
// Check position has been changed or not before doing anything
if(prevLat != position.coords.latitude || prevLong != position.coords.longitude){
// Set previous location
var prevLat = position.coords.latitude;
var prevLong = position.coords.longitude;
// Get current position
var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
document.getElementById("result").innerHTML = positionInfo;
}
}
function startWatch() {
var result = document.getElementById("result");
var toggleWatchBtn = document.getElementById("toggleWatchBtn");
toggleWatchBtn.onclick = function() {
if(watchID) {
toggleWatchBtn.innerHTML = "Start Watching";
navigator.geolocation.clearWatch(watchID);
watchID = false;
} else {
toggleWatchBtn.innerHTML = "Aquiring Geo Location...";
showPosition();
}
}
}
// Initialise the whole system (above)
window.onload = startWatch;
</script>
</head>
<body>
<button type="button" id="toggleWatchBtn">Start Watching</button>
<div id="result">
<!--Position information will be inserted here-->
</div>
</body>
</html>