# geolocation API

Geolocation in the browser runs through two methods

navigator.geolocation.getCurrentPosition(
  successCallback,
  failCallback,
  options
);
navigator.geolocation.watchPosition(successCallback, failCallback, options);
1
2
3
4
5
6

The two functions are the same except that getCurrentPosition runs once and watchPosition runs repeatedly. If you want to stop the watchPosition method running then we call:

navigator.geolocation.clearWatch();
1

Both methods accept a success callback function and a failure callback function. The success function will be passed a position object. The failure callback will be passed a position error object. See the code below for examples.

MDN Position Object reference

MDN PositionError Object reference

The third parameter is the options object.

let options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0,
};
1
2
3
4
5

Codepen Link

MDN options object reference

MDN Geolocation reference

# Google Maps API

Once you are comfortable getting Geolocation coordinates, the next step would be to start working with maps. Google Maps has an API that lets us use a latitude and longitude to display an interactive map of the area.

# Google Maps Geocoding

After you have set up your own account with Google APIs then you can also start using other APIs like the GeoCoding API. The Geocoding API lets you turn an address into a {latitude, longitude} or alternatively turn a {latitude, longitude} into an actual address.

This video will explain how to do some reverse geocoding to extra an address that would have come from the HTML5 geolocation API.

Back to Week main page

Last Updated: 11/1/2020, 7:25:15 PM