javascript - 如何打印 HTML 地理定位?

标签 javascript jquery html css

我正在使用 HTML5 Geolocation 并希望在输入字段中打印返回的用户位置。

这可能吗?如果是怎么办?

    var x = document.getElementById("demo");

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    }

    function showPosition(position) {
      x.innerHTML = "Latitude: " + position.coords.latitude + 
      "<br>Longitude: " + position.coords.longitude;
    }
<input type="text">
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>

最佳答案

I have edited the answer. the problem in your code was that the variable x was coming null since you were trying to do getElemntById for the p tag not defined in the code yet.so I have put the HTML part above the javascript code.


 <input type="text">
    <button onclick="getLocation()">Try It</button>
    <p id="demo"></p>
    <script>
    var x = document.getElementById("demo");
    console.log(x);
       function getLocation() {
         if (navigator.geolocation) {
           navigator.geolocation.getCurrentPosition(showPosition);
         } else {
           x.innerHTML = "Geolocation is not supported by this browser.";
         }
       }

       function showPosition(position) {
         x.innerHTML = "Latitude: " + position.coords.latitude +
         "<br>Longitude: " + position.coords.longitude;
       }
       </script>

关于javascript - 如何打印 HTML 地理定位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56387831/

相关文章:

javascript - 如何开始编写像 mohiomap 这样的东西?

html - 将 IFrame 设置为 "about:blank"的跨浏览器方式?

html - Excel 从 Web 表单中获取数据?

javascript - React 组件结束标签

javascript - 基于正则表达式匹配启用 javascript/jquery 中的按钮

javascript - 在 $.ajax 调用中将附加数据添加到 jQuery 包装的对象数据中

php - 如何删除json数组本身?

jquery - 将 Bootstrap 3.0 Navbar 默认调整大小更改为自定义调整大小

javascript - jquery中 "?"有什么用

javascript - 检测滑动手势 iOS - Cordova/Phonegap Javascript