Melo Noia
By Melo Noia

Javascript Geolocation API

Javascript Geolocation API

Web Geolocation API

This API is used to determine the location of a user in web applications. The user must give the application permission for the location information to be accessed.

Using Geolocation API

The navigator.geolocation object is used together with the getCurrentPosition() to get the user’s current location.

The getCurrentPosition() can succeed or fail. It accepts three callbacks [success, error, options]. The last two callbacks are optional.

1
2
3
4
5
navigator.geolocation.getCurrentPosition(success, error, options);



Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function success(position) {

  console.log(`Latitude : ${position.coords.latitude} Longitude: ${position.coords.longitude}`);

}



function error(err) {

  console.log(`ERROR: ${err.message}`);

}



navigator.geolocation.getCurrentPosition(success, error);