Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Web Geolocation API

Locate the User’s Position

The HTML Geolocation API is used to obtain a user’s geographical position. However, due to privacy concerns, the position is only accessible if the user grants permission.

Note: Geolocation is most accurate on devices with GPS, such as smartphones.

Browser Support

The Geolocation API is supported by all major browsers.

DOM4

Note: The Geolocation API only works in secure contexts like HTTPS. If your site is hosted on an insecure origin (e.g., HTTP), location requests will not work.

Using the Geolocation API

The getCurrentPosition() method is used to retrieve the user’s current location.

The following example returns the latitude and longitude of the user’s position:

Example

<script>
const 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>

Explanation of the example:

 

  • First, check if Geolocation is supported.
  • If supported, call the getCurrentPosition() method; otherwise, show a message to the user.
  • If the getCurrentPosition() method succeeds, it returns a coordinates object to the callback function (showPosition).
  • The showPosition() function then outputs the latitude and longitude.

This example is a simple Geolocation script without error handling.

Handling Errors and Rejections

The second parameter of the getCurrentPosition() method is used to handle errors. It defines a function that will be executed if the attempt to retrieve the user’s location fails.

Example

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;
  }
}

Displaying the Result in a Map

To display the result on a map, you need to use a map service, such as Google Maps.

In the following example, the returned latitude and longitude are used to display the location on a Google Map through a static image.

Example

function showPosition(position) {
  let latlon = position.coords.latitude + “,” + position.coords.longitude;

  let img_url = “https://maps.googleapis.com/maps/api/staticmap?center=
  “
+latlon+“&zoom=14&size=400×300&sensor=false&key=YOUR_KEY”;

  document.getElementById(“mapholder”).innerHTML = “<img src='”+img_url+“‘>”;
}

Location-specific Information

This page has shown how to display a user’s location on a map.

Geolocation is also valuable for providing location-based services such as:

  • Real-time local information
  • Displaying nearby points of interest
  • Turn-by-turn navigation (GPS)

The getCurrentPosition() Method – Return Data

The getCurrentPosition() method returns an object upon success, always including the latitude, longitude, and accuracy properties. Additional properties are returned if available.

Property

Returns

coords.latitude

The latitude as a decimal number (always provided).

coords.longitude

The latitude as a decimal number (always provided).

coords.accuracy

The accuracy of the position (always provided).

coords.altitude

The altitude in meters above sea level (returned if available).

coords.altitudeAccuracy

The accuracy of the altitude position (returned if available).

coords.heading

The heading in degrees clockwise from North (returned if available).

coords.speed

The speed in meters per second (returned when available).

timestamp

The date and time of the response (returned if available).

Geolocation Object – Other interesting Methods

The Geolocation object also provides additional useful methods:

 

  • watchPosition(): Returns the user’s current position and continues to update as the user moves (similar to GPS in a car).
  • clearWatch(): Stops the watchPosition() method.

The example below demonstrates the watchPosition() method. To test this, an accurate GPS device (such as a smartphone) is required.

Example

<script>
const 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>