Geolocation API

The Geolocation API is used to obtain the user's geographic location.

Since this function involves user privacy, the browser will prompt the user whether to agree to give the geographic location, the user may refuse. In addition, this API can only be used in an HTTPS environment.

The browser provides this API through the navigator.geolocation property.

Geolocation Object

The navigator.geolocation property returns a Geolocation object. The object has the following three methods.

  • Geolocation.getCurrentPosition(): Returns a Position object, which represents the current position of the user.
  • Geolocation.watchPosition(): Specify a monitoring function, which will be executed whenever the user's position changes.
  • Geolocation.clearWatch(): Cancel the monitoring function specified by the watchPosition() method.

Geolocation.getCurrentPosition()

The Geolocation.getCurrentPosition() method is used to get the user's location.

navigator.geolocation.getCurrentPosition(success, error, options);

The method accepts three parameters.

  • success: The callback function when the user agrees to give the position, its parameter is a Position object.
  • error: The callback function when the user refuses to give the position, its parameter is a PositionError object. This parameter is optional.
  • options: Parameter object, this parameter is optional.

The Position object has two properties.

  • Position.coords: Returns a Coordinates object, which represents the coordinates of the current position.
  • Position.timestamp: returns an object representing the current timestamp.

The PositionError object has two main properties.

  • PositionError.code: Integer, indicating the cause of the error. 1 means no permission, it may be that the user refuses authorization; 2 means that the location cannot be obtained, and the device may be faulty; 3 means timeout.
  • PositionError.message: a string that represents the description of the error.

The parameter object option can specify three attributes.

  • enableHighAccuracy: Boolean value, whether to return high-precision results. If set to true, it may result in slower response time or increased power consumption (of the mobile device); on the contrary, if set to false, the device can respond more quickly. The default value is false.
  • timeout: A positive integer, indicating the longest time to wait for the query, in milliseconds. The default value is Infinity.
  • maximumAge: a positive integer, representing the maximum acceptable cache time, in milliseconds. If it is set to 0, it means that the cached value is not returned, and the current actual position must be queried; if it is set to Infinity, the cached value must be returned, regardless of how long it has been cached. The default value is 0.

Below is an example.

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0,
};

function success(pos) {
  var crd = pos.coords;

  console.log(`Longitude: ${crd.latitude}`);
  console.log(`Latitude: ${crd.longitude}`);
  console.log(`Error: ${crd.accuracy} meters`);
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);

Geolocation.watchPosition()

The Geolocation.watchPosition() object specifies a monitoring function, which is automatically executed whenever the user's location changes.

navigator.geolocation.watchPosition(success[, error[, options]])

The method accepts three parameters.

  • success: A callback function for monitoring success. The parameter of this function is a Position object.
  • error: This parameter is optional. It represents the callback function that failed to monitor. The parameter of this function is a PositionError object.
  • options: This parameter is optional and indicates the parameter configuration object for monitoring.

This method returns an integer value that represents the number of the monitoring function. This integer is used by the Geolocation.clearWatch() method to cancel the monitoring.

Below is an example.

var id;

var target = {
  latitude: 0,
  longitude: 0,
};

var options = {
  enableHighAccuracy: false,
  timeout: 5000,
  maximumAge: 0,
};

function success(pos) {
  var crd = pos.coords;

  if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
    console.log("Congratulations, you have reached the specified location.");
    navigator.geolocation.clearWatch(id);
  }
}

function error(err) {
  console.warn("ERROR(" + err.code + "): " + err.message);
}

id = navigator.geolocation.watchPosition(success, error, options);

Geolocation.clearWatch()

The Geolocation.clearWatch() method is used to cancel the monitoring function specified by the watchPosition() method. Its parameter is the number of the watch function returned by watchPosition().

navigator.geolocation.clearWatch(id);

See the previous section for an example of how to use it.

Coordinates Object

The Coordinates object is the coordinate interface of geographic location, and the object returned by the Position.coords property is this object.

It has the following attributes, all of which are read-only.

  • Coordinates.latitude: floating point number, representing latitude.
  • Coordinates.longitude: Floating point number, representing longitude.
  • Coordinates.altitude: Floating point number, representing altitude (unit: meter). If not available, return null.
  • Coordinates.accuracy: Floating point number, indicating the accuracy of longitude and latitude (unit: meter).
  • Coordinates.altitudeAccuracy: Floating point number, representing the accuracy of altitude (unit: meter). Return null.
  • Coordinates.speed: Floating point number, indicating the speed of the device (unit: m/s). If not available, return null.
  • Coordinates.heading: Floating point number, indicating the direction the device is heading (unit: degree). The direction is clockwise, the north is 0 degrees, the east is 90 degrees, and the west is 270 degrees. If Coordinates.speed is 0, the heading property returns NaN. If the device cannot provide direction information, this attribute returns null.

Below is an example.

navigator.geolocation.getCurrentPosition(function (position) {
  let lat = position.coords.latitude;
  let long = position.coords.longitude;
  console.log(`Latitude: ${lat.toFixed(2)}`);
  console.log(`Longitude: ${long.toFixed(2)}`);
});