2017-09-22 75 views
2

我目前正在嘗試使用javascript,openstreetmaps和傳單實現一個簡單的地圖。Javascript地理位置找不到位置信息

我的問題來之前,當調用JavaScript的地理位置,並確認瀏覽器上的信息我不斷收到錯誤。我當前的代碼如下:

<html> 

<head> 

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

<script src="https://unpkg.com/[email protected]/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: 

條件結束。任何想法爲什麼這可能會發生?

回答

0

位置信息不可用時調用錯誤。 GeoLocation API根據CELL Towers,Wifi MAC地址,GPS(如果在移動設備上)估算位置。但信息不可用。您的代碼是正確的,請嘗試在其他設備上運行該代碼。