Get User's Location With JavascriptJan 2023
featured image
navigator.geolocation.getCurrentPosition(position => {
  const { latitude, longitude } = position.coords;
  console.log( latitude, longitude )
}, err => {
  console.error(err)
})
c3WEK1WA o

The browser will ask for permission. If user block or don’t give permission, the Geolocation API will not work.

The getCurrentPosition function takes 2 arguments

navigator.geolocation.getCurrentPosition(successCallback, failedCallback);

It’s always better to first check whether the browser supports the Geolocation Web API.

if (window.navigator.geolocation) {
  // Browser supports Geolocation
}