The HTML Geolocation API is used to locate a user’s position. The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.
WebExtensions that wish to use the Geolocation
object must add the "geolocation"
permission to their manifest. The user’s operating system will prompt the user to allow location access the first time it is requested.
How does the HTML5 geolocation API work?
HTML5 geolocation detects latitude and longitude coordinates by using the device’s GPS (if available on the device) or the device’s mobile/WIFI signal (if GPS is not available. The mobile/WIFI signals are triangulated to work out the latitude and longitude.
How accurate is HTML5 geolocation?
Depending on the availability of GPS on the device and the quality of the mobile/WIFI signals, HTML5 geolocation can be very accurate i.e. to a street level. Hence it can be used to pinpoint a device’s location making it a very useful technology for websites or apps that require the exact user’s location to work.
What browsers support HTML5 geolocation?
HTML5 geolocation is widely used and supported on all major browsers:
- Google Chrome (version 5.0 onwards)
- Internet Explorer (version 9.0 onwards)
- Firefox (version 3.5 onwards)
- Safari (version 5.0 onwards)
- Opera (version 16.0 onwards)
Does HTML5 geolocation need user permission?
Yes! HTML5 geolocation is strictly permission-based i.e. the user will be prompted with a browser popup asking to share their device’s location with the website or app being accessed. Only if the user agrees to provide permission, the latitude and longitude coordinates will become available.
It is important to be aware of the implications of permission when designing your location-based website or app in terms of handling cases where the user disagrees with sharing their device location.
A great fallback is the use of IP geolocation technology which utilizes the device’s IP address to work out the approximate location. This method does not require browser permission as the device location detected is only approximate (99%+ accurate on a country level, 70-90% on a state level, and ~70% on a city level)
Demos & tutorials of the HTML5 geolocation API in action (+ Google Maps integrations)
Below is a curated list of some of the best HTML5 geolocation demo’s:
- W3 Schools HTML5 geolocation demo – a simple demo showing how the HTML5 geolocation API requests user permission in the browser and displays the result in a Google Map
- Code Pen demo by Nick Moreton – another simple demo with JavaScript, HTML and css code showing how to make use of the HTML5 geolocation API and display the result in a Google Map
- Tutorial Republic HTML5 geolocation tutorial – Simple guide on how to get visitor coordinates and deal with errors and rejections using JavaScript and HTML. They also provide a guide on how to display the result in a Google map.
- Bit Degree HTML geolocation guide – a detailed guide on how to implement the HTML5 geolocation API in a website.
Demo of how IP geolocation works without needing user permission
See a demo of how IP geolocation works over HTML5 geolocation. You will notice that there is no request from the browser to accept permission for sharing location data with the website. You will also notice how IP geolocation locates the user to the center of a major city rather than to the actual street.
HTML5 geolocation vs IP geolocation
There a significant differences between HTML5 geolocation and IP-based geolocation. The key differences are outlined below:
HTML5 Geolocation
- Uses device’s GPS or mobile/WIFI signals to detect location
- High accuracy (down to street level)
- Requires user permission in the browser
- Has privacy issues as exact location of the user is known
- Used when exactly location of a user is required e.g. locating a user on a map to find travel distances to destination
IP Geolocation
- Uses device’s IP address to match against a IP location database
- 99% accurate on country level, 70-90% on state level, 60-80% on city level
- Does not require any user permission (can auto detect a visitor’s approx. location)
- Less of privacy issue as only approximate location of the user is known
- Used when only approximate location of a user is required e.g. to detect visitor country or state for displaying geo targeted content
Uses cases of HTML5 geolocation
HTML5 geolocation is mainly utilized when the exact location of a user is required for a website or app to function as required. Examples of such use cases are:
- Finding a list of nearby store locations on a map within your city
- Tagging the exact location of a social media post or photo
- To pin point exact location on a map for traffic routing and directions
- Determining exact location to provide weather information in your suburb/zip area
Uses cases of IP geolocation
IP geolocation should be utilized over HTML5 geolocation when the user’s approximate location is sufficient for the website or app to function. Examples of such uses cases are:
- Redirect a website visitor to a country specific website using Geo Redirection
- Display country specific content in a website using a Geo Content tool
- Redirecting instagram product posts to country specific web shop using Geo Links
- Displaying the approximate location of a user in a map using Geo Location
- Blocking a website visitor based on their country, state or city using Geo Blocking
Using HTML Geolocation
The getCurrentPosition()
method is used to return the user’s position.
The example below returns the latitude and longitude of the user’s position:
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} 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>
Handling Errors and Rejections
The second parameter of the getCurrentPosition()
method is used to handle errors. It specifies a function to run if it fails to get the user’s location:
<script>
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>
Location-specific Information
This page has demonstrated how to show a user’s position on a map.
Geolocation is also very useful for location-specific information, like:
- Up-to-date local information
- Showing Points-of-interest near the user
- Turn-by-turn navigation (GPS)
The getCurrentPosition() Method – Return Data
The getCurrentPosition()
method returns an object on success. The latitude, longitude and accuracy properties are always returned. The other properties are returned if available:
Property | Returns |
---|---|
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 position (always returned) |
coords.altitude | The altitude in meters above the mean sea level (returned if available) |
coords.altitudeAccuracy | The altitude accuracy of position (returned if available) |
coords.heading | The heading as degrees clockwise from North (returned if available) |
coords.speed | The speed in meters per second (returned if available) |
timestamp | The date/time of the response (returned if available) |
Geolocation Object – Other interesting Methods
The Geolocation object also has other interesting methods:
watchPosition()
– Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).clearWatch()
– Stops thewatchPosition()
method.
The example below shows the watchPosition()
method. You need an accurate GPS device to test this (like smartphone):
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} 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>
Finding a Visitor’s Coordinates
Getting the position information of the site visitor using the HTML5 geolocation API is fairly simple. It utilizes the three methods that are packed into the navigator.geolocation
object — getCurrentPosition()
, watchPosition()
and clearWatch()
.
The following is a simple example of geolocation that displays your current position. But, first you need to agree to let the browser tell the web server about your position.
<!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>
Dealing with Errors and Rejections
There may be a situation when a user does not want to share his location data with you. To deal with such situations, you can supply two functions when you call the getCurrentLocation()
function.
The first function is called if your geolocation attempt is successful, while the second is called if your geolocation attempt ends in failure. Let’s check out an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Handling Geolocation Errors</title>
<script>
// Set up global variable
var result;
function showPosition() {
// Store the element where the page displays the result
result = document.getElementById("result");
// If geolocation is available, try to get the visitor's position
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
result.innerHTML = "Getting the 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 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>
<div id="result">
<!--Position information will be inserted here-->
</div>
<button type="button" onclick="showPosition();">Show Position</button>
</body>
</html>
Showing Location on Google Map
You can do very interesting things with geolocation data, like showing the user location on Google map. The following example will show your current location on Google map based the latitude and longitude data retrieved 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>
The above example will simply show the location on the Google map using a static image. However, you can also create interactive Google maps with dragging, zoom in/out and other features that you have come across in your real life. Let’s take a look at 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>