Menu Close

How to get my current location on my browser


Here’s a JavaScript function that fetches the current location of a user using the browser’s Geolocation API:

function fetchCurrentLocation() {
  if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(function (position) {
      const latitude = position.coords.latitude;
      const longitude = position.coords.longitude;

      console.log("Latitude: " + latitude);
      console.log("Longitude: " + longitude);

      // You can use the latitude and longitude values here for further processing.
    }, function (error) {
      switch (error.code) {
        case error.PERMISSION_DENIED:
          console.error("User denied the request for Geolocation.");
        case error.POSITION_UNAVAILABLE:
          console.error("Location information is unavailable.");
        case error.TIMEOUT:
          console.error("The request to get user location timed out.");
        case error.UNKNOWN_ERROR:
          console.error("An unknown error occurred.");
  } else {
    console.error("Geolocation is not supported by this browser.");

// Call the function to fetch the current location

This function first checks if the browser supports geolocation. If supported, it uses the getCurrentPosition method to fetch the user’s current position, including latitude and longitude coordinates. It then logs the coordinates to the console, but you can modify the function to do whatever you need with this location information.

Please note that the user’s permission is required to access their location, so the browser will prompt the user for permission when this function is called.


Posted in HTML, JavaScript

You can also read...