Javascript地理位置找不到位置信息

时间:2017-09-22 19:09:01

标签: javascript html5 geolocation openstreetmap

我目前正在尝试使用javascript,openstreetmaps和leaflet实现一个简单的地图。

之前我的问题出现了,当调用javascripts geolocation并确认浏览器上的信息时,我一直收到错误。我目前的代码如下:

<html>

<head>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css"
integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ=="
crossorigin=""/>

<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"
integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log=="
crossorigin=""></script>

<style>
   #mymap {
       width: 100%;
       height: 400px;
       background-color: grey;
       margin-top: 15px;
   }
</style>

<script language="javascript">

function initmap(initialLat, initialLong)
{
   if(!initialLat || !initialLat.length){
   initialLat = 38.01693;
}

if(!initialLong || !initialLong.length){
  initialLong = -8.69475;
}

var mymap = this.mymap = L.map('mymap',{
    center: [initialLat, initialLong],
    zoom: 15
    });

var osmUrl='http://tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';

L.tileLayer(osmUrl, osmAttrib).addTo( mymap );
}

function getMylocation()
{
    if(navigator.geolocation){

    navigator.geolocation.getCurrentPosition(function (position) {

        var lat = position.coords.latitude;
        var long = position.coords.longitude;

        mymap.setView(new L.LatLng(lat, long), 15);

    }, function (error) {
      switch (error.code) {
        case error.PERMISSION_DENIED:
          output.innerHTML += "<p>User denied the request for Geolocation.</p>";
          break;
        case error.POSITION_UNAVAILABLE:
          output.innerHTML += "<p>Location information is unavailable.</p>";
          break;
        case error.TIMEOUT:
          output.innerHTML += "<p>The request to get user location timed out.</p>";
          break;
        case error.UNKNOWN_ERROR:
          output.innerHTML += "<p>An unknown error occurred.</p>";
          break;
      }
    });
  }
}

</script>

</head>

<body onLoad="javascript:initmap();">

<button id="find-near-btn" onClick="getMylocation()">
  Find my location
</button>   

<div id="mymap"></div>
<div id="output"></div>

</body>

</html>

使用按钮调用getMyLocation()函数时,我总是在

中结束
case error.POSITION_UNAVAILABLE:

条件。为什么会发生这种情况的任何想法?

1 个答案:

答案 0 :(得分:0)

位置信息不可用时调用错误。 GeoLocation API根据CELL塔,Wifi MAC地址,GPS(如果在移动设备上)估算位置。但是这些信息不可用。您的代码是正确的,尝试在不同的设备上运行它。

相关问题