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

Aym*_*eem -3 javascript

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

HTML:

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

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

<p id="demo"></p>
Run Code Online (Sandbox Code Playgroud)

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.");
        }
}
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码并单击按钮时,我得到的只是一切.谁知道为什么?

And*_*ggs 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.");
        }
}
Run Code Online (Sandbox Code Playgroud)