我在处理HTML地理位置问题。我实际上想在用户授予权限后每次访问页面时显示当前位置。
即使用户获得了许可,我也可以以经度和纬度的形式显示位置,但是只有当我单击按钮时,才可以显示位置。如何在不单击按钮和重新加载页面的情况下显示位置。 >
旁注:就像Swiggy或Zomato一样,每次我们打开应用程序时都会显示位置。
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}}
答案 0 :(得分:0)
简单的方法是在getLocation()
上调用window.load
。您也可以像这样<body>
那样将其附加到<body onload="getLocation()">
标签上。
var x = document.getElementById("demo");
window.onload = getLocation;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}}