如何重构获取用户当前位置的JS代码?

时间:2019-05-11 20:28:56

标签: javascript geolocation

我对JS并不是最好的选择,并且我有这段代码可以使用地理位置api获取用户的当前坐标。最初,它需要使用许多不同的按钮,但是现在只有一个按钮,因此无需遍历数组。我如何重构该代码以反映这一点?

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.";
  }
}

1 个答案:

答案 0 :(得分:1)

只需定义一个location,然后使用.add-button将单个侦听器添加到一个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.";
  }
});