Geolocation API

Geolocation API

The Geolocation API is used to get the user’s geographic location.

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

Browsers provide this API through the navigator.geolocation property.

Geolocation objects

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

  • Geolocation.getCurrentPosition(): Returns a Position object representing the user’s current position.
  • Geolocation.watchPosition(): Specify a watch function that will be executed whenever the user’s location changes.
  • Geolocation.clearWatch(): Cancels the watch 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 a position, its parameter is a PositionError object. This parameter is optional.
  • options: parameter object, the parameter is optional.

Position objects have two properties.

  • Position.coords: Returns a Coordinates object representing 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 representing the reason for the error. 1 means no permission, it is possible that the user refuses to authorize; 2 means that the location cannot be obtained, maybe the device is faulty; 3 means timeout.
  • PositionError.message: String representing the description of the error.

The parameter object option can specify three properties.

  • enableHighAccuracy: boolean, whether to return high accuracy results. If set to true, it may result in slower response times or increased power consumption (of mobile devices); conversely, if set to false, the device can respond more quickly. The default value is false.
  • timeout: A positive integer, indicating the maximum time to wait for a query, in milliseconds. The default value is Infinity.
  • maximumAge: A positive integer representing the maximum acceptable cache time in milliseconds. If 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, no matter 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} m`);
}

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

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

Geolocation.watchPosition()

The Geolocation.watchPosition() object specifies a watch function that is automatically executed whenever the user’s location changes.

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

The method accepts three parameters.

  • success: Monitor the successful callback function, the parameter of this function is a Position object.
  • error: This parameter is optional, indicating the callback function of the monitoring failure. The parameter of this function is a PositionError object.
  • options: This parameter is optional and indicates the parameter configuration object of the listener.

This method returns an integer value representing the number of the listener function. This integer is used by the Geolocation.clearWatch() method to cancel the watch.

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 watch function specified by the watchPosition() method. Its argument 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 the geographic location, and the Position.coords property returns this object.

It has the following properties, all read-only properties.

  • Coordinates.latitude: A floating point number representing latitude.
  • Coordinates.longitude: float, representing longitude.
  • Coordinates.altitude: A float representing the altitude (unit: meters). Returns null if not available.
  • Coordinates.accuracy: A floating point number representing the accuracy of longitude and latitude (unit: meters).
  • Coordinates.altitudeAccuracy: Floating point number representing the accuracy of altitude (unit: meters). Return null.
  • Coordinates.speed: float, indicating the speed of the device (unit: m/s). Returns null if not available.
  • Coordinates.heading: A floating point number that indicates the heading direction of the device (unit: degrees). The directions are clockwise, 0 degrees to the north, 90 degrees to the east, and 270 degrees to the west. If Coordinates.speed is 0, the heading property returns NaN. If the device cannot provide orientation information, this property 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)}`);
});

Reference link