HTML 哪种方法可以获取用户的当前位置
在本文中,我们将讨论在HTML文档中获取用户当前位置的方法。我们将使用Navigator geolocation属性来实现。Navigator geolocation属性用于由浏览器返回地理位置对象,该对象可用于在HTML文档中定位用户的位置。这是一个只读属性,仅在用户批准的情况下可用,因为它可能会危及用户的隐私。
语法:
navigator.geolocation
为了获取用户的当前位置,我们将使用可在导航器地理位置属性中使用的 getCurrentPosition()方法 。 getCurrentPosition()方法 用于获取用户的当前位置。
语法:
navigator.geolocation.getCurrentPosition(success, error, options);
参数值:
- success: 当getCurrentPosition()方法成功获取数据后调用的函数。
- error: 当发生警告或错误时执行的函数。
- options: 这是一个对象,帮助我们设置可选的timeout、enableHighAccuracy和maximumAge属性。
请参考HTML地理位置文章以获取详细的属性、方法及其实现。
示例1: 下面的例子演示如何使用Geolocation getCurrentPosition()方法获取用户的当前位置。
HTML
<!DOCTYPE html>
<html>
<head>
<script>
// Success function
function successFunction(value) {
var lat = value.coords.latitude;
var long = value.coords.longitude;
document.getElementById('error')
.innerHTML = "";
document.getElementById('latitude')
.innerHTML = `Latitude: {lat}`;
document.getElementById('longitude')
.innerHTML = `Latitude:{long}`;
}
// Error Function
function errorFunction(err) {
document.getElementById('latitude')
.innerHTML = "";
document.getElementById('longitude')
.innerHTML = "";
document.getElementById('error')
.innerHTML = `Error occurred: ${err.message}`;
}
// Main function to get location
function getLocation() {
navigator.geolocation
.getCurrentPosition(
successFunction, errorFunction
);
}
</script>
</head>
<body>
<center>
<h1 style="color : green">
GeeksforGeeks
</h1>
<div>
<button onclick="getLocation()">
Get Location
</button>
<h2 id="latitude"></h2>
<h2 id="longitude"></h2>
<h2 id="error"></h2>
</div>
</center>
</body>
</html>
输出:
示例2: 下面的示例说明了timeout参数在Geolocation getCurrentPosition()方法中的工作原理。
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#timeout {
width: 300px;
height: 30px;
margin: 10px;
font-size: 20px;
}
</style>
<script>
// Success function
function successFunction(value) {
var lat = value.coords.latitude;
var long = value.coords.longitude;
document.getElementById('error')
.innerHTML = "";
document.getElementById('latitude')
.innerHTML = `Latitude: {lat}`;
document.getElementById('longitude')
.innerHTML = `Latitude:{long}`;
}
// Error Function
function errorFunction(err) {
document.getElementById('latitude')
.innerHTML = "";
document.getElementById('longitude')
.innerHTML = "";
document.getElementById('error')
.innerHTML = `Error occurred: ${err.message}`;
}
// Main function to get location
function getLocation() {
const timeOut = document
.getElementById('timeout').value;
const options = {
timeout: timeOut == "" ? 5000 : timeOut
}
navigator
.geolocation
.getCurrentPosition(
successFunction, errorFunction, options
);
}
</script>
</head>
<body>
<center>
<h1 style="color : green">GeeksforGeeks</h1>
<div>
<input id="timeout" type="number"
placeholder="Enter the timeout in milliseconds">
<br />
<button onclick="getLocation()">
Get Location
</button>
<h2 id="latitude"></h2>
<h2 id="longitude"></h2>
<h2 id="error"></h2>
</div>
</center>
</body>
</html>
输出: