Notes on Day 21 of 30 Days of JavaScript

Table of Contents

Lessons Learned

The Navigator.geolocation read-only property returns a Geolocation object that gives Web content access to the location of the device. This allows a Web site or app to offer customized results based on the user’s location.

const geolocator = navigator.geolocation;

Geolocation.watchPosition()

The Geolocation method watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function.

const geolocator = navigator.geolocation;
geolocator.watchPosition((data) => {
  console.log(data.coords.latitude);
  console.log(data.coords.longitude);
}, (error) => {
  console.error('Error occurred: ', error);
});

The data returned is of a GeolocationPosition type with the following structure:

GeolocationPosition
  coords: GeolocationCoordinates
    accuracy: 50.0
    altitude: null
    altitudeAccuracy: null
    heading: null
    latitude: 11.11
    longitude: 11.11
    speed: null
    [[Prototype]]: GeolocationCoordinates
  timestamp: 11111111111111
  [[Prototype]]: GeolocationPosition

References

Twitter, LinkedIn