如何重构此JS地理位置代码



我有一些代码使用JS地理定位对象来查找用户的当前位置。当用户单击一个按钮时,它会用他们的坐标填充一个表单字段。他们可以通过单击不同的按钮,从而填写不同的表单字段,在多个位置执行此操作。我希望这是有道理的。。。

我现在的代码不是很枯燥,但我不知道如何重构它

var firstLocation = document.getElementById("coordinates1");
var secondLocation = document.getElementById("coordinates2");
var thirdLocation = document.getElementById("coordinates3");
// Check if Geolocation is supported, if not, show message
function getLocation1() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition1);
} else { 
firstLocation.innerHTML = "Geolocation is not supported by this browser.";
}
}
function getLocation2() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition2);
} else { 
secondLocation.innerHTML = "Geolocation is not supported by this browser.";
}
}
function getLocation3() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition3);
} else { 
thirdLocation.innerHTML = "Geolocation is not supported by this browser.";
}
}
// outputs the Latitude and Longitude
function showPosition1(position) {
firstLocation.value = position.coords.latitude + 
", " + position.coords.longitude;
}
function showPosition2(position) {
secondLocation.value = position.coords.latitude + 
", " + position.coords.longitude;
}
function showPosition3(position) {
thirdLocation.value = position.coords.latitude + 
", " + position.coords.longitude;
}

和我的HTML:

<div class="col-xs-12 instructions-wrapper">
<p class="form-instructions">1. Add starting point coordinates </p>
<div class="add-button" onclick="getLocation1()">+</div>
</div> <!-- end of instructions wrapper -->
<div class="col-xs-8 form-input">
<%= f.input :start_point, label: false,  input_html: { id: 'coordinates1' } %>
</div>

并且对于CCD_ 1和CCD_。

一个选项是为locations使用一个数组,然后在单击时查找适当的索引。您还应该使用Javascript而不是内联属性正确地附加处理程序,这通常被认为是非常糟糕的做法,并导致难以管理代码。

假设每个location都有一个.add-button,您可以使用为每个按钮添加一个监听器

const locations = ["coordinates1", "coordinates2", "coordinates3"]
.map(id => document.getElementById(id));
// in newer browsers you can forEach directly over the NodeList, but for older browsers
// you'll either need to call `Array.prototype.forEach` or use a polyfill
Array.prototype.forEach.call(
document.querySelectorAll('.add-button'),
(button, i) => {
button.addEventListener('click', () => getLocation(i));
}
);

这将使用单击按钮的索引(与您想要的location的索引相同(调用getLocation。然后,在getLocation中,只检索该索引处的元素:

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

请注意,divs没有有意义的getLocation20 s,并且仅应在插入HTML标记时使用innerHTML,而应使用textContent

最新更新