【问题标题】:Load geolocation into inputbox将地理位置加载到输入框
【发布时间】:2014-11-14 05:09:45
【问题描述】:

我的网页上有一个功能可以获取用户的地理位置。如何在不使用OnClick功能的情况下,在页面加载时自动将经纬度加载到输入框中?

function showlocation() {
   // One-shot position request.
   navigator.geolocation.getCurrentPosition(callback);
}

function callback(position) {
   document.getElementById('latitude').innerHTML = position.coords.latitude;
   document.getElementById('longitude').innerHTML = position.coords.longitude;
}

【问题讨论】:

    标签: javascript html geolocation


    【解决方案1】:
    function showlocation() {
      navigator.geolocation.getCurrentPosition(callback);
    }
    
    function callback(position) {
      document.getElementById('latitude').value = position.coords.latitude;
      document.getElementById('longitude').value = position.coords.longitude;
    }
    
    window.onload = function () {
      showlocation();
    }
    
      <input type="text" id="latitude">
      <input type="text" id="longitude">
    

    【讨论】:

      【解决方案2】:

      这行代码会监听所有 HTML 的加载时间,并在 DOM 准备好被操作时立即调用 showLocation。

      window.addEventListener('DOMContentLoaded', showLocation);
      

      您接受的答案确实有效,但 DOMContentLoaded 通常更快,这为您提供了响应更快的 UI。

      支持证明: Difference between DOMContentLoaded and Load events

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多