What is a Geolocation API?

The Geolocation API is a JavaScript scripting interface that makes it easy to retrieve the geographical location information stored on a device or web browser. It is called when there is a need to programmatically configure a web application based on the user’s location and common use cases include realtime map navigation, serving contextual advertisements, implementing user security checks, and tailoring content to certain regions.

The API does not store any information in itself, but rather provides the ability to gather existing information from the device being queried. It can collect location info from sources such IP Address, GPS, WiFi, Bluetooth, RFID, GSM/CDMA ID, or user input. Once an API query is completed, a “best-guess” location with coordinates is returned to the calling application in JSON.

Geolocation API Properties

The Geolocation API can be accessed with the Geolocation property as part of the Navigator object. The Geolocation property includes a set of three methods, namely:

  • getCurrentPosition() – Retrieves the device location data and stores the coordinates (latitude + longitude), altitude (if available), and accuracy in a Position object which can be used in a callback function. Second and third optional arguments can be set to specify: 1) an error callback and, 2) the desired level of accuracy, the timeout value, and the maximum age to cache position data.
  • watchPosition() – Starts a watch operation which adds the current position to a Position object, and polls the device for system events that indicate any changes in location. When new location data is available, the Position object is updated to reflect the new position. As in getCurrentPosition(), one can optionally set an error callback and extra options (accuracy, timeout, and max age).
  • clearWatch() – Stops an ongoing watch operation specified by the operation’s WatchID. WatchIDs are originally assigned to a watch operation when calling the watchPosition() method.

All major web browsers (Firefox, Chrome, Safari, Opera) support the Geolocation API and it is in extensive use on mobile devices such as Android, iOS, Windows Phone, and Maemo.

Try PubNub Today