Get your users geolocation position in JavaScript

Written by Tom Wells on

This simple code snippet will allow you to get your users' geolocation position using JavaScript. Change the success and error message to do something with the data (e.g. display it on the page).

This will also create a pop-up on the users' browser to request location access.

const success = (position) => {

const error = (error) => {

navigator.geolocation.getCurrentPosition(success, error)

In this case, the success function will log the position to the console and the data will look like this:

GeolocationPosition {
  cords: GeolocationCoordinates,
  timestamp: 1575291200000
coords: GeolocationCoordinates
accuracy: 1234.5678900987654
altitude: null
altitudeAccuracy: null
heading: null
latitude: -37.814
longitude: 144.96332
speed: null