← Back to HTML Course | Chapter 7: Advanced APIs & Features | Lesson 3 of 11

HTML Geolocation

Imagine searching for nearby restaurants on your computer, but instead of typing in your zip code, the website automatically figures out exactly where you are standing. It is like having a digital tour guide in your browser. The HTML Geolocation API does exactly that. It bridges the gap between your browser and your device's GPS or network, allowing your web applications to find your coordinates. This is incredibly useful for building custom maps, showing local weather, or finding nearby services dynamically.

Understanding Geolocation

The Geolocation API allows web applications to request the user's geographic coordinates. The browser uses cell towers, Wi-Fi networks, and GPS sensors to determine your position.

Note: Geolocation is a secure API that requires explicit user permission before sharing any location data.

Warning: This API only works on secure HTTPS connections to protect user privacy.

Example: Understanding Geolocation

markup
<script>
  if (navigator.geolocation) {
    console.log('Geolocation is supported');
  }
</script>

Getting the Current Position

To find the user's exact coordinates, you use the getCurrentPosition method. This method requests the user's location and returns their latitude and longitude coordinates upon success.

Note: Use a clear on-screen prompt to explain to your visitors why your tool needs their location.

Warning: The location request can take a few seconds on mobile devices with weak GPS signals.

Example: Getting the Current Position

markup
<script>
  navigator.geolocation.getCurrentPosition(function (position) {
    console.log(position.coords.latitude, position.coords.longitude);
  });
</script>

Handling Permission Denials

Since geolocation is a private API, users can choose to block the location request. Your scripts must handle permission denials and fallback gracefully without crashing your page.

Note: Always write clear, helpful fallback options (like a manual search box) for users who block location sharing.

Warning: If you do not handle errors, your page will freeze when users block location requests.

Example: Handling Permission Denials

markup
<script>
  navigator.geolocation.getCurrentPosition(
    function (position) { console.log(position.coords); },
    function (error) { console.log('Location access denied:', error.message); }
  );
</script>

Real-Time Position Tracking

If you are building an interactive map or navigation app, you need to track the user's location as they move. You can use the watchPosition method to monitor and update their coordinates in real-time.

Note: Always use clearWatch to stop tracking coordinates once your user finishes using the tool to save battery life.

Warning: Real-time tracking can quickly drain mobile device batteries, so use it only when absolutely necessary.

Example: Real-Time Position Tracking

markup
<script>
  const watchId = navigator.geolocation.watchPosition(function (position) {
    console.log(position.coords.latitude, position.coords.longitude);
  });
  navigator.geolocation.clearWatch(watchId);
</script>

Managing Location Accuracy

By default, browsers prioritize speed over precision. You can pass configuration options (like enableHighAccuracy) to force the browser to use high-precision GPS sensors to determine your position.

Note: Set enableHighAccuracy to true when building precise maps, but keep it false for simple country location lookups.

Warning: Enabling high accuracy can cause the location request to take longer to process.

Example: Managing Location Accuracy

markup
<script>
  navigator.geolocation.getCurrentPosition(
    function (position) { console.log(position.coords); },
    function (error) { console.log(error); },
    { enableHighAccuracy: true }
  );
</script>

watchPosition vs getCurrentPosition

getCurrentPosition asks for the user's location a single time and stops. watchPosition keeps monitoring and calls your callback function repeatedly every time the user's location changes, which is what live tracking features like a map showing a moving delivery need.

Note: Always call clearWatch when you no longer need live updates, such as when a user navigates away from a tracking page, to save battery.

Warning: Leaving watchPosition running indefinitely drains a mobile user's battery noticeably faster, since it keeps the GPS radio active.

Example: watchPosition vs getCurrentPosition

markup
<script>
  navigator.geolocation.getCurrentPosition(pos => console.log('Once:', pos.coords));
  const id = navigator.geolocation.watchPosition(pos => console.log('Updated:', pos.coords));
</script>

Privacy Considerations

Location data is highly sensitive personal information, so browsers always require explicit user permission before sharing it, and that permission can be revoked at any time. Sites should only request location when there is a clear, obvious reason the user will understand, like showing nearby stores.

Note: Explain why you need the user's location in your own interface text before triggering the browser's permission prompt, so users are not caught off guard.

Warning: Requesting location access immediately when a page loads, with no context, is a major reason users distrust and deny geolocation permission requests.

Example: Privacy Considerations

markup
<button onclick="navigator.geolocation.getCurrentPosition(pos => console.log(pos))">
  Show nearby stores
</button>
Common Mistakes
  1. Attempting to test geolocation on insecure HTTP domains, causing browsers to block the API.
  2. Failing to handle permission denials, which can freeze your scripts when users block location requests.
  3. Forgetting to stop watchPosition tracking, which drains mobile device batteries.
Chapter Summary
  • The Geolocation API allows web applications to request user coordinates securely over HTTPS.
  • Use getCurrentPosition to find coordinates once, and watchPosition to track movement in real-time.
  • Always handle permission denials and configure timeout options to keep your scripts running smoothly.
Browser Support

Standard Geolocation API features are natively supported by all modern web browsers.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.