What is geolocation in javascript?

The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

WebExtensions that wish to use the Geolocation object must add the "geolocation" permission to their manifest. The user's operating system will prompt the user to allow location access the first time it is requested.

Concepts and usage

You will often want to retrieve a user's location information in your web app, for example to plot their location on a map, or display personalized information relevant to their location.

The Geolocation API is accessed via a call to navigator.geolocation; this will cause the user's browser to ask them for permission to access their location data. If they accept, then the browser will use the best available functionality on the device to access this information [for example, GPS].

The developer can now access this location information in a couple of different ways:

  • Geolocation.getCurrentPosition[]: Retrieves the device's current location.
  • Geolocation.watchPosition[]: Registers a handler function that will be called automatically each time the position of the device changes, returning the updated location.

In both cases, the method call takes up to three arguments:

  • A mandatory success callback: If the location retrieval is successful, the callback executes with a GeolocationPosition object as its only parameter, providing access to the location data.
  • An optional error callback: If the location retrieval is unsuccessful, the callback executes with a GeolocationPositionError object as its only parameter, providing access information on what went wrong.
  • An optional object which provides options for retrieval of the position data.

For further information on Geolocation usage, read Using the Geolocation API.

Interfaces

Geolocation

The main class of this API — contains methods to retrieve the user's current position, watch for changes in their position, and clear a previously-set watch.

GeolocationPosition

Represents the position of a user. A GeolocationPosition instance is returned by a successful call to one of the methods contained inside Geolocation, inside a success callback, and contains a timestamp plus a GeolocationCoordinates object instance.

GeolocationCoordinates

Represents the coordinates of a user's position; a GeolocationCoordinates instance contains latitude, longitude, and other important related information.

GeolocationPositionError

A GeolocationPositionError is returned by an unsuccessful call to one of the methods contained inside Geolocation, inside an error callback, and contains an error code and message.

Navigator.geolocation

The entry point into the API. Returns a Geolocation object instance, from which all other functionality can be accessed.

Examples

Specifications

Specification
Geolocation API
# geolocation_interface

Browser compatibility

BCD tables only load in the browser

Availability

As Wi-Fi-based locating is often provided by Google, the vanilla Geolocation API may be unavailable in China. You may use local third-party providers such as Baidu, Autonavi, or Tencent. These services use the user's IP address and/or a local app to provide enhanced positioning.

See also

The Geolocation API is used to retrieve the user's location, so that it can for example be used to display their position using a mapping API. This article explains the basics of how to use it.

The geolocation object

The Geolocation API is available through the navigator.geolocation object.

If the object exists, geolocation services are available. You can test for the presence of geolocation thusly:

if ['geolocation' in navigator] {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}

Getting the current position

To obtain the user's current location, you can call the getCurrentPosition[] method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.

Note: By default, getCurrentPosition[] tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data [IP location or Wi-Fi] may be returned to getCurrentPosition[].

navigator.geolocation.getCurrentPosition[[position] => {
  doSomething[position.coords.latitude, position.coords.longitude];
}];

The above example will cause the doSomething[] function to execute when the location is obtained.

Watching the current position

If the position data changes [either by device movement or if more accurate geo information arrives], you can set up a callback function that is called with that updated position information. This is done using the watchPosition[] function, which has the same input parameters as getCurrentPosition[]. The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional just as it is for getCurrentPosition[], can be called repeatedly.

const watchID = navigator.geolocation.watchPosition[[position] => {
  doSomething[position.coords.latitude, position.coords.longitude];
}];

The watchPosition[] method returns an ID number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the clearWatch[] method to stop watching the user's location.

navigator.geolocation.clearWatch[watchID];

Fine tuning the response

Both getCurrentPosition[] and watchPosition[] accept a success callback, an optional error callback, and an optional options object.

This object allows you to specify whether to enable high accuracy, a maximum age for the returned position value [up until this age it will be cached and reused if the same position is requested again; after this the browser will request fresh position data], and a timeout value that dictates how long the browser should attempt to get the position data for, before it times out.

A call to watchPosition could look like:

function success[position] {
  doSomething[position.coords.latitude, position.coords.longitude];
}

function error[] {
  alert['Sorry, no position available.'];
}

const options = {
  enableHighAccuracy: true,
  maximumAge: 30000,
  timeout: 27000
};

const watchID = navigator.geolocation.watchPosition[success, error, options];

Describing a position

The user's location is described using a GeolocationPosition object instance, which itself contains a GeolocationCoordinates object instance.

The GeolocationPosition instance contains only two things, a coords property that contains the GeolocationCoordinates instance, and a timestamp property that contains a DOMTimeStamp instance representing the time at which the position data was retrieved.

The GeolocationCoordinates instance contains a number of properties, but the two you'll use most commonly are latitude and longitude, which are what you need to draw your position on a map. Hence many Geolocation success callbacks look fairly simple:

function success[position] {
  const latitude  = position.coords.latitude;
  const longitude = position.coords.longitude;

  // Do something with your latitude and longitude
}

You can however get a number of other bits of information from a GeolocationCoordinates object, including altitude, speed, what direction the device is facing, and an accuracy measure of the altitude, longitude, and latitude data.

Handling errors

The error callback function, if provided when calling getCurrentPosition[] or watchPosition[], expects a GeolocationPositionError object instance as its first parameter. This object type contains two properties, a code indicating what type of error has been returned, and a human-readable message that describes what the error code means.

You could use it like so:

function errorCallback[error] {
  alert[`ERROR[${error.code}]: ${error.message}`];
};

Examples

In the following example the Geolocation API is used to retrieve the user's latitude and longitude. If successful, the available hyperlink is populated with an openstreetmap.org URL that will show their location.

body {
  padding: 20px;
  background-color: #ffffc9;
}

button {
  margin: 0.5rem 0;
}

HTML

Show my location


JavaScript

function geoFindMe[] {

  const status = document.querySelector['#status'];
  const mapLink = document.querySelector['#map-link'];

  mapLink.href = '';
  mapLink.textContent = '';

  function success[position] {
    const latitude  = position.coords.latitude;
    const longitude = position.coords.longitude;

    status.textContent = '';
    mapLink.href = `//www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
    mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
  }

  function error[] {
    status.textContent = 'Unable to retrieve your location';
  }

  if [!navigator.geolocation] {
    status.textContent = 'Geolocation is not supported by your browser';
  } else {
    status.textContent = 'Locating…';
    navigator.geolocation.getCurrentPosition[success, error];
  }

}

document.querySelector['#find-me'].addEventListener['click', geoFindMe];

Result

What is geolocation used for?

Geolocation makes it possible, from any device connected to the Internet, to obtain all types of information in real time and locate the user with pinpoint accuracy at a given point in time. Geolocation technology is the foundation for location-positioning services and location-aware applications [apps].

What is geolocation example?

Geolocation data generally fulfills one or more of three functions. The most common example is providing the location of an object on Earth through longitude and latitude coordinates. It can also add location information to a digital artifact such as a photo or social media post.

What is geolocation code?

The HTML Geolocation API is used to get the geographical position of a user. Since this can compromise privacy, the position is not available unless the user approves it. Try It. Note: Geolocation is most accurate for devices with GPS, like smartphones.

What is the difference between geolocation and location?

This is because the location is expressed in terms of latitude and longitude coordinates. Geolocation is a stark contrast to GeoIP. While Geolocation uses different information sources to reveal a user's location, geolocation by IP relies specifically on the internet protocol address.

Chủ Đề