Complete HTML Lesson

The Geolocation API

This lesson explains the Geolocation API from the very beginning and then moves into practical coding, useful options, common errors, privacy concerns, and interesting real-world applications. It also includes direct links to the most relevant MDN documentation pages.

1. What is the Geolocation API?

The Geolocation API is a browser feature that allows a web page to ask for the user's geographical position. In simple words, it helps a website know where the user is, usually in the form of latitude, longitude, accuracy, and sometimes speed, heading, altitude, and a timestamp.

The main overview page on MDN is: Geolocation API.

This API is commonly used in map-based websites, route finders, delivery systems, travel tools, attendance systems, location sharing pages, emergency tools, and nearby search applications.

Important idea: the Geolocation API does not directly show a map by itself. It only gives location data. You can then use that data with map libraries like Leaflet or services like OpenStreetMap.

2. How does it work?

When a site wants your location, it asks the browser. The browser then checks whether the user allows it. If permission is granted, the browser tries to determine the position using one or more of these sources:

GPS

Very useful on phones and tablets. Often gives accurate outdoor location.

Wi-Fi Networks

Nearby Wi-Fi information can help estimate the user's location.

Mobile Towers

Useful when GPS is weak or unavailable.

IP Address

Usually less accurate, but may provide a rough area or city.

Accuracy depends on the device, browser, network, environment, and permissions. Indoor results are often less accurate than outdoor results.

3. Before using it: important conditions

If you open a location page directly as a plain file from your computer, some browsers may not allow geolocation. It is usually better to test using localhost or an HTTPS website.

MDN also documents the entry point for the feature as Navigator.geolocation.

4. Main Geolocation API methods

A. getCurrentPosition()

This method gets the user's current position once. It is useful when you just need one location reading.

MDN reference: Geolocation.getCurrentPosition()

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);

Example

navigator.geolocation.getCurrentPosition( function(position) { console.log("Latitude:", position.coords.latitude); console.log("Longitude:", position.coords.longitude); }, function(error) { console.log("Error:", error.message); } );

B. watchPosition()

This method keeps watching the user's position and calls your success function again whenever the location changes. It is useful for live tracking.

MDN reference: Geolocation.watchPosition()

const watchId = navigator.geolocation.watchPosition(successCallback, errorCallback, options);

Example

const watchId = navigator.geolocation.watchPosition( function(position) { console.log("Updated Latitude:", position.coords.latitude); console.log("Updated Longitude:", position.coords.longitude); }, function(error) { console.log("Watch error:", error.message); } );

C. clearWatch()

This method stops a live watch created by watchPosition().

MDN reference: Geolocation interface

navigator.geolocation.clearWatch(watchId);

5. Understanding the position object

When geolocation succeeds, your callback receives a position object. The most important values are inside position.coords.

MDN references: GeolocationPosition, timestamp, longitude, accuracy

Property Meaning
position.coords.latitude The north-south position on Earth.
position.coords.longitude The east-west position on Earth.
position.coords.accuracy Estimated accuracy in meters.
position.coords.altitude Height above sea level, if available.
position.coords.heading Direction of travel, if available.
position.coords.speed Speed in meters per second, if available.
position.timestamp When the reading was taken.

Example

navigator.geolocation.getCurrentPosition(function(position) { const c = position.coords; console.log("Latitude:", c.latitude); console.log("Longitude:", c.longitude); console.log("Accuracy:", c.accuracy); console.log("Altitude:", c.altitude); console.log("Heading:", c.heading); console.log("Speed:", c.speed); console.log("Timestamp:", position.timestamp); });

6. Geolocation options

Both getCurrentPosition() and watchPosition() can accept an options object. MDN documents these option fields on the method pages for getCurrentPosition() and watchPosition().

const options = { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 };
Option Meaning
enableHighAccuracy If true, the browser tries to get more accurate results. This may use more battery and may be slower.
timeout Maximum time in milliseconds to wait for a reading.
maximumAge How old a cached location can be before the browser must fetch a fresh one.

Example

navigator.geolocation.getCurrentPosition( function(position) { console.log(position.coords.latitude, position.coords.longitude); }, function(error) { console.log(error.message); }, { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 } );
Use enableHighAccuracy: true when accuracy matters a lot, such as route tracking or attendance by location. Use lower accuracy or cached values when saving battery is more important.

7. Handling errors properly

Location requests can fail. So a good application must always handle errors.

MDN references: GeolocationPositionError, error.code, error.message

function handleError(error) { switch (error.code) { case error.PERMISSION_DENIED: console.log("User denied location permission."); break; case error.POSITION_UNAVAILABLE: console.log("Location information is unavailable."); break; case error.TIMEOUT: console.log("The request to get location timed out."); break; default: console.log("An unknown error occurred."); } }
Error code Meaning
1 / PERMISSION_DENIED The user blocked location access.
2 / POSITION_UNAVAILABLE The browser could not determine the position.
3 / TIMEOUT The location request took too long.
Never assume location will always work. Build your page so that it remains useful even if location is not available.

8. Privacy, security, and ethics

Location is sensitive information. A responsible developer must handle it carefully.

Good design is not only technical. It also respects the user's trust.

For permission-related background, MDN also has: Using the Permissions API.

9. Basic example: get current location

This is the classic beginner example. It checks if geolocation exists, then asks for one position reading.

<script> if ("geolocation" in navigator) { navigator.geolocation.getCurrentPosition( function(position) { alert( "Latitude: " + position.coords.latitude + "\\nLongitude: " + position.coords.longitude ); }, function(error) { alert("Error: " + error.message); } ); } else { alert("Geolocation is not supported in this browser."); } </script>

10. Example: live tracking with watchPosition()

This is useful when the user's location keeps changing, such as during walking, driving, or route recording.

let watchId = null; function startTracking() { watchId = navigator.geolocation.watchPosition( function(position) { console.log("Live:", position.coords.latitude, position.coords.longitude); }, function(error) { console.log("Tracking error:", error.message); }, { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 } ); } function stopTracking() { if (watchId !== null) { navigator.geolocation.clearWatch(watchId); watchId = null; } }

11. Example: opening the location on a map

Once you have latitude and longitude, you can build a map link.

navigator.geolocation.getCurrentPosition(function(position) { const lat = position.coords.latitude; const lng = position.coords.longitude; const url = `https://www.openstreetmap.org/?mlat=${lat}&mlon=${lng}#map=16/${lat}/${lng}`; window.open(url, "_blank"); });

This combines the Geolocation API with a map platform. The API provides coordinates, and the map platform shows the place visually.

12. Interesting and useful applications of the Geolocation API

1. Current location sharing

A user presses a button and shares a map link with a friend, family member, or colleague.

2. Nearby places finder

Find nearby schools, hospitals, hotels, temples, shops, or bus stands.

3. Route recorder

Save movement points over time and draw the journey on a map.

4. Best path finder

Combine current location with mapping and routing services to suggest routes.

5. Delivery tracking

Track drivers, delivery people, or field workers in real time.

6. Attendance by area

Mark attendance only if the user is physically present in a defined place.

7. Travel diary

Record the places a traveler visits and create a journey timeline.

8. Emergency help button

Send the current position to emergency contacts quickly.

9. Weather by current place

Use current coordinates to fetch local weather information.

10. Local tourism guide

Show nearby attractions, pilgrimage stops, museums, or heritage points.

11. Fitness and walk tracker

Measure walking routes, running paths, and total distance traveled.

12. Smart local apps

Build area-based notifications, check-ins, and personalized local dashboards.

14. Live demo inside this lesson

This demo lets you request your current position once, or start live tracking. It also shows the most important values returned by the browser.

Latitude
Longitude
Accuracy
Altitude
Heading
Speed
Timestamp
Status
Ready
This demo will work best on HTTPS or localhost. If permission is denied, the page will still remain usable and explain what happened.
Lesson demo loaded.

15. Final summary

The Geolocation API is one of the most practical browser APIs because it connects the digital world to the user's real-world position. With just a few lines of code, a web page can:

The most important things to remember are:

  1. Always request permission respectfully.
  2. Always handle errors properly.
  3. Use HTTPS or localhost.
  4. Protect the user's privacy.
  5. Combine geolocation with maps and routing for richer applications.
A very good next step after learning the Geolocation API is to combine it with OpenStreetMap and Leaflet to create live route, location sharing, and nearby search tools.