代码之家  ›  专栏  ›  技术社区  ›  Cláudio Ribeiro

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

  •  1
  • Cláudio Ribeiro  · 技术社区  · 7 年前

    <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 回复  |  直到 7 年前
        1
  •  0
  •   user5229708 user5229708    7 年前

    位置信息不可用时调用Error。地理定位API根据蜂窝塔、Wifi MAC地址、GPS(如果在移动设备上)估计位置。但信息不可用。您的代码是正确的,请尝试在不同的设备上运行。