Javascript 简明教程
JavaScript - Geolocation API
Geolocation API
Geolocation API 是一种 Web API,提供 JavaScript 接口以访问用户地理位置数据。Geolocation API 包含可在你的网站上用于访问用户位置的各种方法和属性。
The Geolocation API is a web API that provides a JavaScript interface to access the user’s geographical location data. A Geolocation API contains the various methods and properties that you can use to access the user’s location on your website.
使用设备的 GPS 检测用户所在位置。位置的准确性取决于 GPS 设备的准确性。
It detects the location of the user’s using the device’s GPS. The accuracy of the location depends on the accuracy of the GPS device.
由于位置信息会危害用户的隐私,因此它在访问位置之前会要求获得许可。如果用户授予许可,网站就可以访问纬度、经度等信息。
As location compromises the users' privacy, it asks for permission before accessing the location. If users grant permission, websites can access the latitude, longitude, etc.
有时,开发人员需要在网站上获取用户的位置。例如,如果你正在创建类似 Ola 和 Uber 的应用程序,则需要了解用户的位置,以便接送他们乘坐。
Sometimes, developers need to get the user’s location on the website. For example, if you are creating an Ola, Uber, etc. type applications, you need to know the user’s location to pick them up for the ride.
Geolocation API 允许用户与特定网站共享位置。
The Geolocation API allows users to share the location with a particular website.
Real-time use cases of the Geolocation API
以下是 Geolocation API 的实时用例。
Here are the real-time use cases of the Geolocation API.
-
To get the user’s location coordinates, show them on the map.
-
To tag the user’s location on the photograph.
-
To suggest nearby stores, food courts, petrol pumps, etc., to users.
-
To get the current location for the product or food delivery.
-
To pick up users for the ride from their current location.
Using the Geolocation API
若要使用地理位置 API,可以使用窗口对象的“navigator”属性。Navigator 对象包含“geolocation”属性,该属性包含各种属性和用于操作用户位置的方法。
To use the Geolocation API, you can use the 'navigator' property of the window object. The Navigator object contains the 'geolocation' property, containing the various properties and methods to manipulate the user’s location.
Syntax
按照以下语法使用地理位置 API。
Follow the syntax below to use the Geolocation API.
var geolocation = window.navigator.geolocation;
OR
var geolocation = navigator.geolocation;
在此,地理位置对象可让你访问位置坐标。
Here, the geolocation object allows you to access the location coordinates.
Example: Checking the browser support
使用 navigator,你可以检查用户的浏览器是否支持 Geolocation.geolocation 属性。
Using the navigator, you can check whether the user’s browser supports the Geolocation.geolocation property.
下面的代码会根据地理位置是否得到支持来对应地打印消息。
The code below prints the message accordingly whether the Geolocation is supported.
首先,我们将数据转换为 JSON 格式。然后,我们将数据转换为字符串并在网页上打印。
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<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.
Geolocation Methods
以下是地理位置 API 的方法。
Here are the methods of the Geolocation API.
Method |
Description |
getCurrentPosition() |
It is used to retrieve the current geographic location of the website user. |
watchPosition() |
It is used to update the user’s live location continuously. |
clearWatch() |
To clear the ongoing watch of the user’s location using the watchPosition() method. |
The Location Properties
getCurrentPosition() 方法会执行你作为参数传递的回调函数。该回调函数取对象作为一个参数。参数对象包含有关用户位置信息的不同属性。
The getCurrentPosition() method executes the callback function you passed as an argument. The callback function takes the object as a parameter. The parametric object contains various properties with information about the user’s location.
在此,我们在下表中列出了位置对象的所有属性。
Here, we have listed all properties of the location object in the table below.
Property |
Type |
Description |
coords |
objects |
It is an object you get as a parameter of the callback function of the getCurrentPosition() method. It contains the below properties. |
coords.latitude |
Number |
It contains the latitude of the current location in decimal degrees. The value range is [-90.00, +90.00]. |
coords.longitude |
Number |
It contains the longitude of the current location in decimal degrees. The value range is [-180.00, +180.00]. |
coords.altitude |
Number |
It is an optional property, and it specifies the altitude estimate in meters above the WGS 84 ellipsoid. |
coords.accuracy |
Number |
It is also optional and contains the accuracy of the latitude and longitude estimates in meters. |
coords.altitudeAccuracy |
Number |
[Optional]. It contains the accuracy of the altitude estimate in meters. |
coords.heading |
Number |
[Optional]. It contains information about the device’s current direction of movement in degrees counting clockwise relative to true north. |
coords.speed |
Number |
[Optional]. It contains the device’s current ground speed in meters per second. |
timestamp |
date |
It contains the information about the time when the location information was retrieved, and the Position object created. |
Getting User’s Location
您可以使用 getCurrentPosition() 方法获取用户的当前位置。
You can use the getCurrentPosition() method to get the user’s current location.
Syntax
用户可以遵循以下语法以使用 getCurrentPosition() 方法获取用户的当前位置。
Users can follow the syntax below to get the user’s current position using the getCurrentPosition() method.
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
Parameters
getCurrentPosition() 对象采用 3 个参数。
The getCurrentPosition() object takes 3 parameters.
-
successCallback − This function will be called when the method successfully retrieves the user’s location.
-
errorCallback − This function will be called when the method throws an error while accessing the user’s location.
-
Options − It is an optional parameter. It is an object containing properties like timeout, maxAge, etc.
Permitting the website to access your location
每当任何网站尝试访问您的位置时,浏览器都会弹出权限警报框。如果您单击“允许”,它可以获取您的位置详细信息。否则,它会抛出错误。
Whenever any website tries to access your location, the browser pops up the permission alert box. If you click the 'allow’, it can fetch your location details. Otherwise, it throws an error.
您可以在下图中看到权限弹出窗口。
You can see the permission pop-up in the image below.
Example
在以下代码中,我们使用 getCurrentPosition() 方法以获取用户的位置。该方法调用getCords() 函数以获取当前位置。
In the below code, we use the getCurrentPosition() method to get the user’s location. The method calls the getCords() function to get the current location.
在getCords() 函数中,我们打印cords 对象各种属性的值。
In the getCords() function, we print the value of the various properties of the cords object.
首先,我们将数据转换为 JSON 格式。然后,我们将数据转换为字符串并在网页上打印。
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<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>
Geolocation Errors
getCurrentPosition() 方法将回调函数作为第二个参数以处理错误。回调函数可以将错误对象作为参数。
The getCurrentPosition() method takes the callback function as a second parameter to handle the error. The callback function can have an error object as a parameter.
在以下情况下,可能会发生错误。
In the below cases, an error can occur.
-
When the user has denied access to the location.
-
When location information is not available.
-
When the request for the location is timed out.
-
It can also generate any random error.
以下是错误对象属性的列表。
Here is the list of properties of the error object.
Property |
Type |
Description |
code |
Number |
It contains the error code. |
message |
String |
It contains the error message. |
以下是不同错误代码的列表。
Here is the list of different error codes.
Code |
Constant |
Description |
0 |
UNKNOWN_ERROR |
When methods of the geolocation object can’t retrieve the location, it returns the code 0 for unknown error. |
1 |
PERMISSION_DENIED |
When the user has denied the permission to access the location. |
2 |
POSITION_UNAVAILABLE |
When it can’t find the location of the device. |
3 |
TIMEOUT |
When the method of the geolocation object can’t find the user’s position. |
Example: Error Handling
我们在下面的代码中使用 findLocation() 函数中的 getCurrentPosition() 方法。我们已将 errorCallback() 函数传递为 getCurrentPosition() 方法的第二个参数,以处理错误。
We use the getCurrentPosition() method in the findLocation() function in the below code. We have passed the errorCallback() function as a second parameter of the getCurrentPosition() method to handle the errors.
在 errorCallback() 函数中,我们使用 switch case 语句,根据错误代码打印不同的错误消息。
In the errorCallback() function, we use the switch case statement to print the different error messages based on the error code.
当您单击找出位置按钮时,它将向您显示一个弹出框,要求访问地址的权限。如果您单击“阻止”,它将向您显示一个错误。
When you click the Find Location button, it will show you a pop-up asking permission to access the location. If you click on the 'block’, it will show you an error.
首先,我们将数据转换为 JSON 格式。然后,我们将数据转换为字符串并在网页上打印。
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<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>
Geolocation Options
getCurrentPosition() 方法将包含选项的对象作为一个第三参数。
The getCurrentPosition() method takes the object containing the options as a third parameter.
以下是您可以传递给选项对象的键形式的选项的列表。
Here is the list of options you can pass as a key to the option object.
Property |
Type |
Description |
enableHighAccuracy |
Boolean |
It represents whether you want to get the most accurate location. |
timeout |
Number |
It takes a number of milliseconds as a value for that much time you want to wait to fetch the location data. |
maximumAge |
Number |
It takes the milliseconds as a value, specifying the maximum age of the cached location. |
Example
下面的代码将查找最准确的地址。此外,我们已将毫秒数设置为 options 对象的最大年龄和超时属性。
The below code finds the most accurate location. Also, we have set milliseconds to the maximumAge, and timeout properties of the options object.
首先,我们将数据转换为 JSON 格式。然后,我们将数据转换为字符串并在网页上打印。
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<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>
Watching the Current Location of the User
watchPosition() 方法允许您跟踪用户的实时地址。它返回一个 ID,我们可以在您想停止跟踪用户时使用 clearWatch() 方法。
The watchPosition() method allows you to track the live location of users. It returns the ID, which we can use with the clearWatch() method when you want to stop tracking the user.
Syntax
按照以下语法,使用 watchPosition() 方法来跟踪用户的实时地址。
Follow the syntax below to use the watchPosition() method to track the live location of users.
var id = navigator.geolocation.watchPosition(successCallback, errorCallback, options)
errorCallback 和 options 是可选参数。
The errorCallback and options are optional arguments.
如果您想要停止追踪用户,您可以按照以下指令执行。
If you want to stop tracking the user, you can follow the syntax below.
navigator.geolocation.clearWatch(id);
clearWatch() 方法将 watchPosition() 方法返回的 ID 作为其参数。
The clearWatch() method takes the id returned by the watchPosition() method as an argument.
Example
在下面的代码中,我们使用地理位置对象的 watchPosition () 方法来获取用户的连续位置。
In the below code, we used the geolocation object’s watchPosition () method to get the user’s continuous position.
我们使用 getCords() 函数作为 watchPosition() 方法的回调,在这里打印用户位置的经度和维度。
We used the getCords() function as a callback of the watchPosition() method, where we print the latitude and longitude of the user’s position.
在 findLocation() 方法中,我们使用 setTimeOut() 方法在 30 秒后停止追踪。
In the findLocation() method, we used the setTimeOut() method to stop tracking after 30 seconds.
在输出中,您可以看到代码多次打印用户的的位置。
In the output, you can observe that the code prints the user’s position multiple times.
首先,我们将数据转换为 JSON 格式。然后,我们将数据转换为字符串并在网页上打印。
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<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); // Stop tracking after 30 seconds.
} 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>