地理位置 API
Geolocation API 是一个 Web API,它提供了一个 JavaScript 接口来访问用户的地理位置数据。Geolocation API 包含可用于访问用户在网站上位置的各种方法和属性。
它使用设备的 GPS 检测用户的位置。位置的准确性取决于 GPS 设备的准确性。
由于位置会损害用户的隐私,因此它会在访问位置之前请求权限。如果用户授权,网站可以访问纬度、经度等。
有时,开发人员需要获取用户在网站上的位置。例如,如果您正在创建 Ola、Uber 等类型的应用程序,则需要知道用户的位置才能接他们上车。
Geolocation API 允许用户与特定网站共享位置。
Geolocation API 的实时用例
以下是 Geolocation API 的实时用例。
- 要获取用户的位置坐标,请在地图上显示它们。
- 在照片上标记用户的位置。
- 向用户推荐附近的商店、美食广场、加油站等。
- 获取产品或食品配送的当前位置。
- 从用户的当前位置接载用户。
使用 Geolocation API
要使用 Geolocation API,您可以使用 window 对象的 'navigator' 属性。Navigator 对象包含 'geolocation' 属性,其中包含用于操作用户位置的各种属性和方法。
语法
请按照以下语法使用 Geolocation API。
var geolocation = window.navigator.geolocation;
OR
var geolocation = navigator.geolocation;
在这里,geolocation 对象允许您访问位置坐标。
示例:检查浏览器支持
使用导航器,您可以检查用户的浏览器是否支持 Geolocation.geolocation 属性。
下面的代码会相应地打印消息,说明是否支持 Geolocation。
首先,我们将数据转换为 JSON 格式。之后,我们将数据转换为字符串并将其打印在网页上。
<html>
<body>
<div id = "output"> </div>
<script>
const output = document.getElementById("output");
if (navigator.geolocation) {
output.innerHTML += "Geolocation is supported by your browser."
} else {
output.innerHTML += "Geolocation is not supported by your browser."
}
</script>
</body>
</html>
输出
地理位置方法
以下是 Geolocation API 的方法。
方法 | 描述 |
---|---|
getCurrentPosition() | 用于检索网站用户的当前地理位置。 |
watchPosition() | 用于持续更新用户的实时位置。 |
clearWatch() | 使用 watchPosition() 方法清除对用户位置的持续监视。 |
位置属性
getCurrentPosition() 方法执行您作为参数传递的回调函数。回调函数将对象作为参数。参数化对象包含各种属性以及有关用户位置的信息。
在这里,我们在下表中列出了 location 对象的所有属性。
属性 | Type | 描述 |
---|---|---|
coords | objects | 作为 getCurrentPosition() 方法的回调函数的参数获取的对象。它包含以下属性。 |
coords.latitude | Number | 包含当前位置的纬度(以十进制度为单位)。取值范围为 [-90.00, +90.00]。 |
coords.longitude | Number | 包含当前位置的经度(以十进制度为单位)。取值范围为 [-180.00, +180.00]。 |
coords.altitude | Number | 是一个可选属性,用于指定 WGS 84 椭球体上方的高度估计值(以米为单位)。 |
coords.accuracy | Number | 它也是可选的,并且包含以米为单位的纬度和经度估计的准确性。 |
coords.altitudeAccuracy | Number | [可选]。它包含高度估计的精度(以米为单位)。 |
coords.heading | Number | [可选]。它包含有关设备当前移动方向的信息(以相对于正北顺时针方向计数的度数)。 |
coords.speed | Number | [可选]。它包含设备的当前地面速度(以米/秒为单位)。 |
timestamp | date | 它包含有关检索位置信息和创建 Position 对象的时间的信息。 |
获取用户的位置
您可以使用 getCurrentPosition() 方法获取用户的当前位置。
语法
用户可以按照以下语法使用 getCurrentPosition() 方法获取用户的当前位置。
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
参数
getCurrentPosition() 对象接受 3 个参数。
- successCallback − 当该方法成功检索到用户的位置时,将调用此函数。
- errorCallback − 当方法在访问用户位置时引发错误时,将调用此函数。
- options − 它是一个可选参数。它是一个包含 timeout 、 maxAge 等属性的对象。
允许网站访问您的位置
每当任何网站尝试访问您的位置时,浏览器都会弹出权限警报框。如果您单击“允许”,它可以获取您的位置详细信息。否则,它会引发错误。
您可以在下图中看到权限弹出窗口。
例在下面的代码中,我们使用 getCurrentPosition() 方法来获取用户的位置。该方法调用 getCords() 函数来获取当前位置。
在 getCords() 函数中,我们打印 cords 对象的各种属性的值。
首先,我们将数据转换为 JSON 格式。之后,我们将数据转换为字符串并将其打印在网页上。
<html>
<body>
<h3> Location Information </h3>
<button onclick = "findLocation()"> Find Location </button>
<p id = "output"> </p>
<script>
const output = document.getElementById("output");
function findLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getCords); //
}
else {
output.innerHTML += "Geo Location is not supported by this browser!";
}
}
// 回调函数
function getCords(coords) {
output.innerHTML += "The current position is: <br>";
output.innerHTML += "Latitude: " + coords.coords.latitude + "<br>";
output.innerHTML += "Longitude: " + coords.coords.longitude + "<br>";
output.innerHTML += "Accuracy: " + coords.coords.accuracy + "<br>";
output.innerHTML += "Altitude: " + coords.coords.altitude + "<br>";
}
</script>
</body>
</html>
地理位置错误
getCurrentPosition() 方法将回调函数作为第二个参数来处理错误。回调函数可以将 error 对象作为参数。
在以下情况下,可能会发生错误。
- 当用户拒绝访问该位置时。
- 当位置信息不可用时。
- 当对位置的请求超时时。
- 它还可以生成任何随机错误。
下面是 error 对象的属性列表。
属性 | Type | 描述 |
---|---|---|
code | Number | 它包含错误代码。 |
message | String | 它包含错误消息。 |
以下是不同错误代码的列表。
Code | Constant | 描述 |
---|---|---|
0 | UNKNOWN_ERROR | 当 geolocation 对象的方法无法检索位置时,它会返回代码 0 表示未知错误。 |
1 | PERMISSION_DENIED | 当用户拒绝访问该位置的权限时。 |
2 | POSITION_UNAVAILABLE | 当它找不到设备的位置时。 |
3 | TIMEOUT | 当 geolocation 对象的方法找不到用户的位置时。 |
示例:错误处理
在下面代码的 findLocation() 函数中使用 getCurrentPosition() 方法。我们已将 errorCallback() 函数作为 getCurrentPosition() 方法的第二个参数传递来处理错误。
在 errorCallback() 函数中,我们使用 switch case 语句根据错误代码打印不同的错误消息。
当您单击“查找位置”按钮时,它将显示一个弹出窗口,询问访问该位置的权限。如果您单击 'block',它将向您显示一个错误。
首先,我们将数据转换为 JSON 格式。之后,我们将数据转换为字符串并将其打印在网页上。
<html>
<body>
<div id = "output"> </div>
<button onclick = "findLocation()"> Find Location </button>
<script>
const output = document.getElementById("output");
function findLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getCords, errorCallback); //
}
else {
output.innerHTML += "Geo Location is not supported by this browser!";
}
}
// 回调函数
function getCords(coords) {
output.innerHTML += "The current position is: <br>";
output.innerHTML += "Latitude: " + coords.coords.latitude + "<br>";
output.innerHTML += "Longitude: " + coords.coords.longitude + "<br>";
}
// 处理错误的功能
function errorCallback(err) {
switch (err.code) {
case err.PERMISSION_DENIED:
output.innerHTML += "You have denied to access your device's location";
break;
case err.POSITION_UNAVAILABLE:
output.innerHTML += "Your position is not available.";
break;
case err.TIMEOUT:
output.innerHTML += "Request timed out while fetching your location.";
break;
case err.UNKNOWN_ERROR:
output.innerHTML += "Unknown error occurred while fetching your location.";
break;
}
}
</script>
</body>
</html>
地理位置选项
getCurrentPosition() 方法将包含选项的对象作为第三个参数。
以下是您可以作为键传递给 option 对象的选项列表。
属性 | Type | 描述 |
---|---|---|
enableHighAccuracy | Boolean | 它表示您是否要获取最准确的位置。 |
timeout | Number | 对于您要等待获取位置数据的时间,它需要毫秒数作为值。 |
maximumAge | Number | 它以毫秒为值,指定缓存位置的最长期限。 |
例
下面的代码查找最准确的位置。此外,我们还为 options 对象的 maximumAge 和 timeout 属性设置了毫秒。
首先,我们将数据转换为 JSON 格式。之后,我们将数据转换为字符串并将其打印在网页上。
<html>
<body>
<div id = "output"> </div>
<button onclick = "findLocation()"> Find Location </button>
<script>
const output = document.getElementById("output");
function findLocation() {
if (navigator.geolocation) {
// 地理定位选项
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(getCords, errorfunc, options);
}
else {
output.innerHTML += "Geo Location is not supported by this browser!";
}
}
// 回调函数
function getCords(coords) {
output.innerHTML += "The current position is: <br>";
output.innerHTML += "Latitude: " + coords.coords.latitude + "<br>";
output.innerHTML += "Longitude: " + coords.coords.longitude + "<br>";
}
function errorfunc(err) {
output.innerHTML += "The error message is - " + err.message + "<br>";
}
</script>
</body>
</html>
监视用户的当前位置
watchPosition() 方法允许您跟踪用户的实时位置。它返回 ID,当您想停止跟踪用户时,我们可以将其与 clearWatch() 方法一起使用。
语法
按照下面的语法使用 watchPosition() 方法跟踪用户的实时位置。
var id = navigator.geolocation.watchPosition(successCallback, errorCallback, options)
errorCallback 和 options 是可选参数。
如果要停止跟踪用户,可以按照以下语法操作。
navigator.geolocation.clearWatch(id);
clearWatch() 方法将 watchPosition() 方法返回的 id 作为参数。
例在下面的代码中,我们使用了 geolocation 对象的 watchPosition () 方法来获取用户的连续位置。
我们使用 getCords() 函数作为 watchPosition() 方法的回调,在该方法中打印用户位置的纬度和经度。
在 findLocation() 方法中,我们使用 setTimeOut() 方法在 30 秒后停止跟踪。
在输出中,您可以观察到代码多次打印用户的位置。
首先,我们将数据转换为 JSON 格式。之后,我们将数据转换为字符串并将其打印在网页上。
<html>
<body>
<button onclick = "findLocation()"> Find Location </button>
<div id = "output"> </div>
<script>
let output = document.getElementById("output");
function findLocation() {
if (navigator.geolocation) {
let id = navigator.geolocation.watchPosition(getCoords);
setTimeout(function () {
navigator.geolocation.clearWatch(id);
output.innerHTML += "<br>Tracking stopped!";
}, 30000); // 30秒后停止跟踪。
} else {
output.innerHTML += "<br>Geo Location is not supported by this browser!";
}
}
// Callback function
function getCoords(location) {
let latitude = location.coords.latitude;
let longitude = location.coords.longitude;
output.innerHTML += `<br> Latitude: ${latitude}, Longitude: ${longitude}`;
}
</script>
</body>
</html>