为什么位置确定在JavaScript中不起作用?

时间:2016-10-12 02:36:43

标签: javascript

我想用以下代码显示用户的位置:

HTML:

<p>Click the button to get your coordinates.</p>

<input type="button" value="try it" onclick="getLocation()" />

<p id="demo"></p>

JavaScript:

function getLocation() {
        if (navigator.geolocation) {
             navigator.geolocation.getCurrentPosition(
               function showPosition(position) 
                 {alert("Latitude: ");},
                    function error1(){},
                      {enableHighAccuracy: true, timeout: 5000});
        } else {
            alert("Geolocation is not supported by this browser.");
        }
}

当我运行上面的代码并单击按钮时,我得到的一切都没有。谁知道为什么?

2 个答案:

答案 0 :(得分:5)

对于错误回调函数,您需要提供更详细的错误报告:

var browserGeolocationFail = function(error) {
  switch (error.code) {
    case error.TIMEOUT:
      alert("Browser geolocation error !\n\nTimeout.");
      break;
    case error.PERMISSION_DENIED:
      if(error.message.indexOf("Only secure origins are allowed") == 0) 
      {
          alert('Only secure origins are allowed');
      }
      else
      {
          alert("Please enable location services on.");
      }
      break;
    case error.POSITION_UNAVAILABLE:
      alert("Browser geolocation error !\n\nPosition unavailable.");
      break;
  }
};

function getLocation() 
{
        if (navigator.geolocation) 
        {
            navigator.geolocation.getCurrentPosition(
                function showPosition(position) {alert("Latitude: ");},
                browserGeolocationFail,
                {enableHighAccuracy: true, timeout: 5000});
        }   
        else 
        {
            alert("Geolocation is not supported by this browser.");
        }
}

答案 1 :(得分:0)

  

最后的脚本元素将被解析   用户单击该按钮。 (虽然在结束后它不应该   </html>代码。) - @nnnnnn

另请注意,此警告记录在console

getCurrentPosition() and watchPosition() no longer work on insecure origins. 
To use this feature, you should consider switching your application to a secure origin, such as HTTPS.

plnkr https://plnkr.co/edit/VR1lFgL7mY0bsxZVt6tc?p=preview

&#13;
&#13;
<!DOCTYPE html>
<html>
<body>

<p>Click the button to get your coordinates.</p>

<input type="button" value="try it" onclick="getLocation()" />

<p id="demo"></p>
<script>
var x = document.getElementById("demo"); 

function getLocation() {
        if (navigator.geolocation) {
        alert("in getLocation"); navigator.geolocation.getCurrentPosition(function showPosition(position) {alert("Latitude: ");},function error1(){},{enableHighAccuracy: true, timeout: 5000});
        } else {
            alert("Geolocation is not supported by this browser.");
        }
}


</script>
</body>
</html>
&#13;
&#13;
&#13;