Search code examples
javascriptgeolocation

How can I refactor this JS code that fetches a user's current location?


I'm not the best with JS and I have this code that fetches a user's current coordinates using the geolocation api. Initially it needed to work with many different buttons, but now there is only one button so no need to iterate over an array. How could I refactor this code to reflect this?

var locations = ["coordinatesStore"]
  .map(id => document.getElementById(id));

Array.prototype.forEach.call(
  document.querySelectorAll('.add-button'),
  (button, i) => {
    button.addEventListener('click', () => getLocation(i));
  }
);

function getLocation(i) {
  var location = locations[i];
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(({ coords: { latitude, longitude }}) => {
      location.value = latitude + ", " + longitude;
    });
  } else { 
    location.value = "Geolocation is not supported by this browser.";
  }
}

Solution

  • Just define the one location, and add a single listener to the one .add-button with querySelector:

    const location = document.getElementById('coordinatesStore');
    document.querySelector('.add-button').addEventListener('click', () => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(({ coords: { latitude, longitude }}) => {
          location.value = latitude + ", " + longitude;
        });
      } else { 
        location.value = "Geolocation is not supported by this browser.";
      }
    });