Skip to content
JavaScript

Geolocation

Get user geolocation information.

By EZ4Code Team
geolocationgeolocation

Code

function getPosition() {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) return reject(new Error("Geolocation not supported"));
    navigator.geolocation.getCurrentPosition(
      pos => resolve({
        lat: pos.coords.latitude,
        lng: pos.coords.longitude,
        accuracy: pos.coords.accuracy
      }),
      err => reject(err),
      { enableHighAccuracy: true, timeout: 10000 }
    );
  });
}

Explanation

Wraps the Geolocation API in Promise form.

More JavaScript Snippets