w3resource

Geolocation API in JavaScript for user Location Access

JavaScript Event Handling: Exercise-19 with Solution

Geolocation API Example

Write a JavaScript program that uses the Geolocation API to display the user's current location.

Solution 1: Using Geolocation API with Callbacks

HTML and JavaScript Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>w3resource</title>
</head>
<body>
<script>
// Function to get the user's current location using Geolocation API
function getLocation() {
  const output = document.getElementById('output'); // Element to display location info

  // Check if the browser supports Geolocation
  if (!navigator.geolocation) {
    output.textContent = 'Geolocation is not supported by your browser.';
    return;
  }

  // Request the user's location
  navigator.geolocation.getCurrentPosition(
    (position) => {
      // Success callback: Display the coordinates
      const latitude = position.coords.latitude; // Extract latitude
      const longitude = position.coords.longitude; // Extract longitude
      output.textContent = `Latitude: ${latitude}, Longitude: ${longitude}`;
    },
    (error) => {
      // Error callback: Display an error message
      output.textContent = `Error: Unable to retrieve your location (${error.message})`;
    }
  );
}

// Create a button to trigger the location request
const locationButton = document.createElement('button');
locationButton.textContent = 'Get Location'; // Button text
locationButton.onclick = getLocation; // Set click event to trigger getLocation
document.body.appendChild(locationButton); // Add button to the DOM

// Create an element to display the location output
const output = document.createElement('p');
output.id = 'output'; // Set ID for reference
document.body.appendChild(output); // Add output element to the DOM
  
  
  </script>
</body>
</html>

Output:

Get Location
Latitude: 48.8575, Longitude: 2.3514

Explanation:

    1. Geolocation Check:

    • Verifies if the browser supports the Geolocation API before proceeding.

    2. Success Callback:

    • Extracts and displays the user's latitude and longitude when the location is successfully fetched.

    3. Error Handling:

    • Handles errors like user denial or inability to fetch location and displays appropriate messages.

    4. User Interaction:

    • Provides a button for users to explicitly request their location.

Solution 2: Using Geolocation API with Promises

HTML and JavaScript Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>w3resource</title>
</head>
<body>
<script>
// Function to get the user's location using Promises
function getLocation() {
  const output = document.getElementById('output'); // Element to display location info

  // Check if the browser supports Geolocation
  if (!navigator.geolocation) {
    output.textContent = 'Geolocation is not supported by your browser.';
    return;
  }

  // Convert Geolocation API into a Promise-based function
  const getCurrentPosition = () =>
    new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject);
    });

  // Use the Promise to get the location
  getCurrentPosition()
    .then((position) => {
      const latitude = position.coords.latitude; // Extract latitude
      const longitude = position.coords.longitude; // Extract longitude
      output.textContent = `Latitude: ${latitude}, Longitude: ${longitude}`; // Display coordinates
    })
    .catch((error) => {
      output.textContent = `Error: Unable to retrieve your location (${error.message})`; // Display error
    });
}

// Create a button to trigger the location request
const locationButton = document.createElement('button');
locationButton.textContent = 'Get Location'; // Button text
locationButton.onclick = getLocation; // Set click event to trigger getLocation
document.body.appendChild(locationButton); // Add button to the DOM

// Create an element to display the location output
const output = document.createElement('p');
output.id = 'output'; // Set ID for reference
document.body.appendChild(output); // Add output element to the DOM
 
  </script>
</body>
</html>

Output:

Get Location
Latitude: 48.8575, Longitude: 2.3514

Explanation:

    1. Promise-Based Geolocation:

    • Converts the Geolocation API's callback-based approach into a Promise for cleaner syntax.

    2. Chaining:

    • Uses then and catch to handle success and errors, respectively, in a structured way.

    3. Error Handling:

    • Displays detailed error messages when the location cannot be fetched.

    4. User Interaction:

    • Includes a button for the user to initiate the location request.

Live Demo:

See the Pen javascript-event-handling-exercise-19 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that retrieves the user's current latitude and longitude using the Geolocation API and displays them on a map.
  • Write a JavaScript function that fetches the user's geolocation, then uses a reverse geocoding API to display the city name.
  • Write a JavaScript program that monitors the user's position in real time using the Geolocation API and updates the display accordingly.
  • Write a JavaScript function that handles geolocation permission errors and displays a custom error message if access is denied.

Go to:


PREV : Fetch API with Error Handling.
NEXT : Clipboard API for Copy.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.