Menu
×
     ❯   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING

HTML Tutorial

HTML HOME HTML Introduction HTML Editors HTML Basic HTML Elements HTML Attributes HTML Headings HTML Paragraphs HTML Styles HTML Formatting HTML Quotations HTML Comments HTML Colors HTML CSS HTML Links HTML Images HTML Favicon HTML Page Title HTML Tables HTML Lists HTML Block & Inline HTML Div HTML Classes HTML Id HTML Iframes HTML JavaScript HTML File Paths HTML Head HTML Layout HTML Responsive HTML Computercode HTML Semantics HTML Style Guide HTML Entities HTML Symbols HTML Emojis HTML Charsets HTML URL Encode HTML vs. XHTML

HTML Forms

HTML Forms HTML Form Attributes HTML Form Elements HTML Input Types HTML Input Attributes Input Form Attributes

HTML Graphics

HTML Canvas HTML SVG

HTML Media

HTML Media HTML Video HTML Audio HTML Plug-ins HTML YouTube

HTML APIs

HTML Web APIs HTML Geolocation HTML Drag and Drop HTML Web Storage HTML Web Workers HTML SSE

HTML Examples

HTML Examples HTML Editor HTML Quiz HTML Exercises HTML Website HTML Syllabus HTML Study Plan HTML Interview Prep HTML Bootcamp HTML Certificate HTML Summary HTML Accessibility

HTML References

HTML Tag List HTML Attributes HTML Global Attributes HTML Browser Support HTML Events HTML Colors HTML Canvas HTML Audio/Video HTML Doctypes HTML Character Sets HTML URL Encode HTML Lang Codes HTTP Messages HTTP Methods PX to EM Converter Keyboard Shortcuts

HTML Geolocation API


The Geolocation API is used to get the user's current location.


Locate the User's Position

The Geolocation API is used to access the user's current location.

Since this can compromise privacy, the location is not available unless the user approves it.

Note: The Geolocation API is only available on secure contexts such as HTTPS.

Tip: The Geolocation API is most accurate for devices with GPS, like smartphones or smartwatches.


Browser Support

The numbers in the table specify the first browser version that fully supports Geolocation.

API
Geolocation 5.0 12.0 3.5 5.0 10.6

Using HTML Geolocation API

The Geolocation API is accessed via a call to navigator.geolocation. This will cause the browser to ask the user for permission to access their location data. If the user accept, the browser will search for the best available functionality on the device to access this information (for example GPS).

The getCurrentPosition() method is used to return the user's current location.

The example below returns the latitude and longitude of the user's current location:

Example

<script>
const x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function success(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}

function error() {
  alert("Sorry, no position available.");
}
</script>
Try it Yourself »

Example explained:

  • Check if Geolocation is supported
  • If Geolocation is supported, run the getCurrentPosition() method. If not, display a message to the user
  • The success() function outputs the user's location in latitude and longitude
  • The error() function alerts a text if the browser retrieves an error in getCurrentPosition()


Error Handling 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.

Here is an example of a more specific error handling:

Example

function error(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;
  }
}
Try it Yourself »

Location-specific Information

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 location of the user and continues to return updated location as the user moves (like the GPS in a car).
  • clearWatch() - Stops the watchPosition() method.

The example below shows the watchPosition() method. You need an accurate GPS device to test this (like a smartphone):

Example

<script>
const x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(success, error);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function success(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}

function error(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>
Try it Yourself »

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.