Javascript地理位置找不到位置信息
问题描述:
我目前正在尝试使用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:
条件结束。任何想法为什么这可能会发生?
答
位置信息不可用时调用错误。 GeoLocation API根据CELL Towers,Wifi MAC地址,GPS(如果在移动设备上)估算位置。但信息不可用。您的代码是正确的,请尝试在其他设备上运行该代码。