首页 > 解决方案 > 如何打印 HTML 地理位置?

问题描述

我正在使用 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>

标签: javascriptjqueryhtmlcss

解决方案


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>

推荐阅读