我希望每次单击用户时都能获得该用户的地理位置。 这是代码
<script type="text/livescript">
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";}
}
function showPosition(position) {
// x.innerHTML="Latitude: " + position.coords.latitude +
// "<br>Longitude: " + position.coords.longitude;
var latitude = document.getElementById('latitude');
var longitude = document.getElementById('longitude');
latitude.value=position.coords.latitude;
longitude.value=position.coords.longitude;
}
</script>
使用Button拨打电话
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×
</button>
<h4 class="modal-title">Check IN Details</h4>
</div>
当我第一次单击按钮时,浏览器会询问“允许位置”弹出窗口并渲染纬度/经度,并且我正在文本框中显示它们。网址中将会生成一个位置图标,表明该网站正在使用位置
当我再次单击按钮以获取其挂起位置时,我的意思是我需要关闭浏览器并单击按钮以获取经/纬度。
在第二种情况下,它无法获取位置。可能会有一些刷新功能,这些功能可以清除最后一个经/纬度并根据位置获取新的位置。
请帮帮我。
答案 0 :(得分:0)
请参见下面的代码,如果这是您所需要的,我只是使用getCurrentLocation方法而不是watchPosition方法,因为watchPosition会在每次设备位置更改时自动调用。由于您需要手动触发一个函数来获取当前位置,因此您应该使用getCurrentLocation方法,并传递一个具有maximumAge:0的选项以获取一个新的位置,否则将不使用缓存位置,并且将尝试检索实际的当前位置。然后传递的超时值为“ Infinity”,这意味着直到该位置可用,getCurrentPosition()才会返回。参见https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions
<!DOCTYPE html>
<html>
<head></head>
<body>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
</body>
<script>
var x = document.getElementById("demo");
function getLocation() {
var options = {maximumAge: 0, timeout: Infinity, enableHighAccuracy: true};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, errorHandler, options);
} 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 errorHandler (err) {
//TODO: Set your rules what will happen when error occured
console.log(err);
}
</script>
</html>