← Back to Chapters

JavaScript Geolocation

? JavaScript Geolocation

? Quick Overview

The JavaScript Geolocation API allows a website to access the user's geographic location (latitude and longitude) through the browser. It is commonly used for location-based services such as maps, weather apps, and showing nearby stores or events.

Geolocation runs in the browser (client-side) and requires explicit user permission before sharing any location data.

? Key Concepts

  • navigator.geolocation: The main object used to access geolocation features.
  • getCurrentPosition(): Retrieves the user's current position once.
  • Success callback: Function that runs when the location is successfully retrieved and receives a position object.
  • Error callback: Function that runs if something goes wrong and receives an error object with a code and message.
  • Options object: Optional settings like enableHighAccuracy, timeout, and maximumAge to fine-tune how geolocation works.
  • Permissions: The browser will always ask the user to allow or block location access for a site.
  • Asynchronous behavior: Geolocation calls are non-blocking, so you must use callbacks or promises (no immediate return of coordinates).

? Syntax and Flow

The basic flow when using the Geolocation API is:

  1. Check if geolocation is supported using if (navigator.geolocation).
  2. Call navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options).
  3. In the success callback, access position.coords.latitude and position.coords.longitude.
  4. In the error callback, handle errors such as permission denial or timeout.
  5. Optionally, pass an options object to control accuracy, timeouts, and caching.

The position object contains a coords property with details like latitude, longitude, accuracy, altitude (if available), and more.

? Code Examples

? Basic getCurrentPosition() Usage

This example checks for support and then logs the user's latitude and longitude to the console.

? View Code Example
// Check if the browser supports the Geolocation API
if (navigator.geolocation) {
// Request the current position (async)
navigator.geolocation.getCurrentPosition(
// Success callback: runs when location is retrieved
function (position) {
console.log("Latitude:", position.coords.latitude);
console.log("Longitude:", position.coords.longitude);
},
// Error callback: runs if something goes wrong
function (error) {
console.error("Error code:", error.code, "Message:", error.message);
}
);
} else {
// Fallback when Geolocation is not available
console.log("Geolocation is not supported by this browser.");
}

⚙️ Example with Options

Here we pass an options object to request high accuracy, set a timeout, and control how old cached positions can be.

? View Code Example
// Configuration options for the Geolocation request
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};

// Request the current position with success, error callbacks and options
navigator.geolocation.getCurrentPosition(
(pos) => {
console.log("Latitude:", pos.coords.latitude);
console.log("Longitude:", pos.coords.longitude);
},
(err) => {
console.error("Error:", err.message);
},
options
);

? Live Output & Explanation

In most real projects, instead of just logging to the console, you would show the coordinates on the page, pass them to a map service (like Google Maps), or send them to a server for location-based features.

The example below shows a simple interface where the user clicks a button to get their location. The script then displays the latitude and longitude, or an error message, on the screen.

?️ Demo: Get Your Current Location

 

 

? Common Use Cases

  • Showing the user's current position on an interactive map.
  • Displaying local weather, news, or events based on the user's city.
  • Finding nearby restaurants, shops, ATMs, or other points of interest.
  • Providing navigation directions from the user's current location.
  • Location-based personalization in web applications (e.g., auto-selecting country or region).

? Tips & Best Practices

  • Always check if navigator.geolocation exists before using it.
  • Explain why you need the user's location so they feel comfortable granting permission.
  • Handle user denial gracefully with a clear message and a fallback experience.
  • Use enableHighAccuracy only when necessary because it can use more battery and take longer.
  • Set sensible timeout and maximumAge values to avoid hanging requests.
  • Never store or share location data without informing the user and following privacy rules.

? Try It Yourself

  • Create a button that fetches and displays the user's current latitude and longitude in a styled box.
  • Use the coordinates to show the user's location on a Google Map or OpenStreetMap embed.
  • Experiment with different enableHighAccuracy and timeout values and observe the behavior.
  • Display a friendly message when the user denies location access and provide a non-location-based fallback.
  • Add error handling that shows different messages for permission denied vs timeout vs other errors.