HTML Tutorial menu

HTML Geolocation

The Geolocation API lets a page ask the browser for the visitor's location, with their permission.

What It Is Used For

  • Showing the nearest branch of a shop or bank
  • Filling in the delivery address on a food app
  • Showing the local weather
  • Tracking a run or a bike ride

The browser always asks the user first. Nobody's location is shared without them clicking "Allow".

Rules Before You Start

RuleWhy
The page must use https (or localhost while testing)Location is private data
The user must allow itA permission box appears the first time
Ask only after a clickA pop-up on page load looks suspicious, and many users click "Block"
Always handle errorsThe user can say no, or the device may not find a signal

Getting the Position

navigator.geolocation.getCurrentPosition() asks for the location once. You give it two functions: one for success and one for errors.

Example

html
<!DOCTYPE html>
<html>
<body>

<button onclick="findMe()">Find my location</button>
<p id="out">Click the button.</p>

<script>
function findMe() {
  const out = document.getElementById("out");

  if (!("geolocation" in navigator)) {
    out.innerHTML = "Sorry, this browser does not support geolocation.";
    return;
  }

  out.innerHTML = "Looking for you...";
  navigator.geolocation.getCurrentPosition(success, failure);
}

function success(position) {
  const lat = position.coords.latitude.toFixed(4);
  const lon = position.coords.longitude.toFixed(4);
  document.getElementById("out").innerHTML =
    "Latitude: " + lat + "<br>Longitude: " + lon;
}

function failure(error) {
  document.getElementById("out").innerHTML = "Could not get location: " + error.message;
}
</script>

</body>
</html>
Try it Yourself »

If Ayesha runs this on her phone in Karachi and clicks Allow, she sees something like:

Output
Latitude: 24.9056
Longitude: 67.0822

The Try it editor runs code in a locked-down frame that is not allowed to ask for location, so there you will see the error message. That is useful too: it shows the error handling working. Put the page on an https website (or open it from a local server) to see real numbers.

What the Position Contains

PropertyMeaning
coords.latitudeNorth-south position in degrees
coords.longitudeEast-west position in degrees
coords.accuracyHow exact it is, in metres
coords.altitudeHeight above sea level (often null)
coords.speedSpeed in metres per second (often null)
timestampWhen the position was measured

Handling Errors

The error object has a code that tells you what went wrong:

CodeNameMeaning
1PERMISSION_DENIEDThe user clicked Block
2POSITION_UNAVAILABLEThe device could not find its position
3TIMEOUTIt took too long

Example

javascript
function failure(error) {
  let text;
  if (error.code === error.PERMISSION_DENIED) {
    text = "You blocked location. Please type your area instead.";
  } else if (error.code === error.TIMEOUT) {
    text = "This is taking too long. Please try again.";
  } else {
    text = "Your location could not be found.";
  }
  document.getElementById("out").innerHTML = text;
}

Always give the user another way, such as typing their city or area.

Options

A third argument sets options:

Example

javascript
navigator.geolocation.getCurrentPosition(success, failure, {
  enableHighAccuracy: true,  // use GPS if possible (slower, uses more battery)
  timeout: 10000,            // give up after 10 seconds
  maximumAge: 60000          // a position up to 1 minute old is fine
});

Showing the Location on a Map

A simple way to show the result is a link to a map service with the coordinates in the address:

Example

javascript
function success(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  const url = "https://www.google.com/maps?q=" + lat + "," + lon;
  document.getElementById("out").innerHTML =
    '<a href="' + url + '" target="_blank">Open my location on the map</a>';
}

Following a Moving User

watchPosition() calls your function again every time the position changes. It returns an id, which you pass to clearWatch() to stop.

Example

javascript
const watchId = navigator.geolocation.watchPosition(success, failure);

// later, for example when the ride ends:
navigator.geolocation.clearWatch(watchId);

Watching the position all the time uses a lot of battery. Stop it as soon as you no longer need it.

Respect Privacy

Tell users why you need their location, use it only for that, and do not save it without asking. In many countries, location is treated as personal data by law.

Exercise

Exercise

Which method asks for the visitor's location one time?

Learn HTML with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp