【问题标题】:How to print HTML geolocation?如何打印 HTML 地理位置?
【发布时间】:2019-05-31 02:08:59
【问题描述】:

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

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

    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>

【问题讨论】:

  • 您没有任何 ID 为 demo 的 HTML 元素??
  • 对不起,我刚刚编辑了代码。
  • 您的代码对我有用。在 chrome 上,它会在显示我的地理坐标之前弹出并请求许可。你授权了吗? (chrome chrome://settings/content/location?search=permission 中的权限)
  • 当我点击允许时,它不显示纬度或经度。它一直有效,直到弹出许可。

标签: javascript jquery html css


【解决方案1】:
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>

【讨论】:

  • 这是我的代码。它不适用于此。
  • 我已经编辑了答案。您的代码中的问题是变量 x 为空,因为您试图为代码中尚未定义的 p 标记执行 getElemntById。所以我已将 HTML 部分放在 javascript 代码上方。
【解决方案2】:

您可以处理错误以了解根本原因,可能是该位置不可用

Check the way to handle error in this answer

不要先将值直接分配给 x.innerHTML,而是使用 console.log

检查您是否正在获取位置坐标
function showPosition(position) {
         console.log(position)
        // x.innerHTML = "Latitude: " + position.coords.latitude +
        // "<br>Longitude: " + position.coords.longitude;
       }

然后在您成功收到职位详细信息后,将其分配给您的变量

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

【讨论】:

    猜你喜欢
    • 2011-08-28
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多