我目前正在尝试使用 javascript、openstreetmaps 和 leaflet 实现一个简单的 map 。
我的问题早在这之前就出现了,当调用 JavaScript 地理定位并确认浏览器上的信息时,我不断收到错误。我当前的代码如下:
<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:
条件。知道为什么会发生这种情况吗?
最佳答案
当位置信息不可用时,会调用错误。 GeoLocation API 根据 CELL 塔、Wifi MAC 地址、GPS(如果在移动设备上)估计位置。但信息不可用。您的代码是正确的,请尝试在不同的设备上运行它。
关于Javascript地理定位找不到位置信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46371675/