TIL how to get the location of the user with the Geolocation API
POSTED ON:
TAGS: mdn browser javascript permissions
You can get the user's location in the browser.
First, the user has to accept this. As it's a security request.
Second, you use the Geolocation API.
function getLocation() {
if (!navigator.geolocation) {
console.log('Geolocation API not supported by this browser.');
} else {
console.log('Checking location...');
//fire the geolocation with callback functions navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
}
// the two callbacks
function locationSuccess(position) {
console.log(position);
}
function locationError(position) {
console.error('Geolocation error!');
}
You can also set it to watch using the
Geolocation.watchPosition()
via Nathan Pasko's How to Check a User's Location with JavaScript
Related TILs
Tagged: mdn