JavaScript - Geolocation API
地理位置 API
地理位置 API 是一个 Web API,它提供了一个 JavaScript 接口来访问用户的地理位置数据。地理位置 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; 或 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 is supported by your browser.
地理定位方法
以下是地理定位 API 的方法。
| 方法 | 描述 |
|---|---|
| getCurrentPosition() | 用于检索网站用户的当前地理位置。 |
| watchPosition() | 用于持续更新用户的实时位置。 |
| clearWatch() | 使用 watchPosition() 方法清除当前对用户位置的监控。 |
位置属性
getCurrentPosition() 方法会执行您作为参数传递的回调函数。回调函数将对象作为参数。参数对象包含各种属性,其中包含有关用户位置的信息。
下表列出了位置对象的所有属性。
| 属性 | 类型 | 描述 |
|---|---|---|
| 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!";
}
}
// Callback function
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() 方法将回调函数作为第二个参数来处理错误。回调函数可以接收错误对象作为参数。
以下情况下可能会发生错误。
当用户拒绝访问位置信息时。
当位置信息不可用时。
当位置请求超时时。
它还可以生成任何随机错误。
以下是错误对象的属性列表。
| 属性 | 类型 | 描述 |
|---|---|---|
| code | Number | 包含错误代码。 |
| message | String | 包含错误消息。 |
以下是不同错误代码的列表。
| 代码 | 常量 | 描述 |
|---|---|---|
| 0 | UNKNOWN_ERROR | 当地理位置对象的方法无法检索位置时,它会返回表示未知错误的代码 0。 |
| 1 | PERMISSION_DENIED | 当用户拒绝访问该位置的权限时。 |
| 2 | POSITION_UNAVAILABLE | 当无法找到设备。 |
| 3 | TIMEOUT | 当地理位置对象的方法无法找到用户位置时。 |
示例:错误处理
在下面的代码中,我们在 findLocation() 函数中使用 getCurrentPosition() 方法。我们将 errorCallback() 函数作为 getCurrentPosition() 方法的第二个参数传递,以处理错误。
在 errorCallback() 函数中,我们使用 switch case 语句根据错误代码打印不同的错误消息。
当您点击"查找位置"按钮时,它会显示一个弹出窗口,询问您是否有权访问该位置。如果您点击"块",则会显示错误。
首先,我们将数据转换为 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!";
}
}
// Callback function
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 to handle error
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() 方法将包含选项的对象作为第三个参数。
以下是您可以作为键传递给选项对象的选项列表。
| 属性 | 类型 | 描述 |
|---|---|---|
| enableHighAccuracy | 布尔值 | 它表示您是否希望获取最精确的位置。 |
| timeout | 数字 | 它表示您希望等待获取位置的时间(以毫秒为单位)数据。 |
| maximumAge | 数字 | 以毫秒为单位,指定缓存位置的最大时长。 |
示例
以下代码查找最准确的位置。此外,我们将毫秒设置为 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) {
// Options for 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!";
}
}
// Callback function
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,当您想停止追踪用户时,我们可以使用该 ID 和 clearWatch() 方法。
语法
请按照以下语法使用 watchPosition() 方法追踪用户的实时位置。
var id = navigator.geolocation.watchPosition(successCallback, errorCallback, options)
errorCallback 和 options 是可选参数。
如果您想停止追踪用户,可以按照以下语法操作。
navigator.geolocation.clearWatch(id);
clearWatch() 方法将 watchPosition() 方法返回的 id 作为参数。
示例
在下面的代码中,我们使用地理位置对象的 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>

