博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
地理位置api_如何使用地理位置API
阅读量:2510 次
发布时间:2019-05-11

本文共 6594 字,大约阅读时间需要 21 分钟。

地理位置api

The browser exposes a navigator.geolocation object, through which we’ll do all the geolocation operations.

浏览器显示一个navigator.geolocation对象,通过该对象我们将执行所有地理位置操作。

It’s only available on pages served using HTTPS, for security purposes, and it’s available on all modern browsers.

出于安全性考虑,它仅在使用HTTPS服务的页面上可用,并且在所有现代浏览器中都可用。

navigator.geolocation

The geolocation object

Since window is the global object, we can access navigator without specifying window.navigator

由于window是全局对象,因此我们无需指定window.navigator就可以访问navigator

The window.navigator property exposed by browsers points to a Navigator object which is a container object that makes a lot of Web Platform APIs available to us.

浏览器公开的window.navigator属性指向一个Navigator对象 ,该对象是一个容器对象 ,使我们可以使用许多Web Platform API。

The geolocation object provides the following methods:

geolocation对象提供以下方法:

  • getCurrentPosition()

    getCurrentPosition()

  • watchPosition()

    watchPosition()

  • clearWatch()

    clearWatch()

The first one is used to get the current position coordinates. When we call this method for the first time, the browser automatically asks the user for the permission to share this information to us.

第一个用于获取当前位置坐标。 当我们第一次调用此方法时,浏览器会自动询问用户是否允许与我们共享此信息。

This is how this interface looks in Chrome:

这是Chrome中该界面的外观:

The permission screen in Chrome

on Firefox:

在Firefox上:

The permission screen in Firefox

and on Safari:

在Safari上:

The permission screen in Safari

This needs to be done only once per origin. You can change the decision you made, and revert a permission decision. This is how you do so with Chrome, by clicking the lock icon near the domain:

每个起点只需执行一次。 您可以更改您做出的决定,并还原权限决定。 通过使用Chrome,您可以通过以下方法来执行此操作:单击域附近的锁定图标:

Permission details

Once this permission is granted, we can proceed.

授予此权限后,我们可以继续。

获取用户的位置 (Getting the user’s position)

Let’s start with this sample code:

让我们从以下示例代码开始:

navigator.geolocation.getCurrentPosition(() => {})

The permission panel should appear. Allow the permission.

权限面板应出现。 允许权限。

Notice how I passed an empty , because the function wants a callback function.

注意我如何传递一个空 ,因为该函数需要一个回调函数。

This function is passed a Position object, which contains the actual location:

此函数传递一个Position对象,该对象包含实际位置:

navigator.geolocation.getCurrentPosition(position => {  console.log(position)})

This object has 2 properties:

该对象具有2个属性:

  • coords, a Coordinates object

    coords ,一个Coordinates对象

  • timestamp, the when the position was retrieved

    timestamp ,获取位置的

The Coordinates object comes with several properties that define the location:

Coordinates对象带有几个定义位置的属性:

  • accuracy the accuracy of the position measured, expressed in meters

    accuracy测量位置的精度,以米为单位

  • altitude the altitude value measured

    altitude测得的高度值

  • altitudeAccuracy the accuracy of the altitude measured, expressed in meters

    altitudeAccuracy测量的海拔精度,以米为单位

  • heading the direction towards which the device is traveling. Expressed in degrees (0 = North, East = 90, South = 180, West = 270)

    heading设备行进的方向前进。 以度数表示(0 =北,东= 90,南= 180,西= 270)

  • latitude the latitude value measured

    latitude测量的纬度值

  • longitude the longitude value measured

    longitude测量的经度值

  • speed the speed at which the device is traveling, expressed in meters per second

    speed的速度,以米/秒为单位

Depending on the implementation and the device, some of those will be null. For example on Chrome running on my MacBook Air I only got values for accuracy, latitude and longitude.

根据实现和设备的不同,其中一些将为null 。 例如,在我的MacBook Air上运行的Chrome上,我仅获得accuracylatitudelongitude

navigator.geolocation.getCurrentPosition(position => {  console.log(position.coords.latitude)  console.log(position.coords.longitude)})

观察职位变化 (Watching the position for changes)

In addition to getting the user position once, which you can do using getCurrentPosition(), you can use the watchPosition() method of navigator.geolocation to register a callback function that will be called upon each and every change that the device will communicate to us.

除了可以一次使用getCurrentPosition()获取用户位置之外,您还可以使用navigator.geolocationwatchPosition()方法注册一个回调函数,该回调函数将在设备与之通信的每次更改中被调用我们。

Usage:

用法:

navigator.geolocation.watchPosition(position => {	console.log(position)})

Of course the browser will ask for the permission also with this method, if it was not already granted.

当然,如果尚未授予该权限,浏览器也会使用此方法来请求该权限。

We can stop watching for a position by calling the navigator.geolocation.clearWatch() method, passing it the id returned by watchPosition():

我们可以通过调用navigator.geolocation.clearWatch()方法并将其传递给watchPosition()返回的id来停止监视位置:

const id = navigator.geolocation.watchPosition(position => {	console.log(position)})//stop watching after 10 secondssetTimeout(() => {  navigator.geolocation.clearWatch(id)}, 10 * 1000)

如果用户拒绝许可 (If the user denies the permission)

Remember the permission popup window the browser shows when we call one of the methods to get the position?

还记得我们调用其中一种方法获取位置时浏览器显示的权限弹出窗口吗?

If the user denies that, we can intercept this scenario by adding an error handling function, as the second parameter to the methods getCurrentPosition() and watchPosition().

如果用户拒绝,我们可以通过添加错误处理函数作为方法getCurrentPosition()watchPosition()的第二个参数来拦截这种情况。

navigator.geolocation.getCurrentPosition(position => {  console.log(position)}, error => {	console.error(error)})

The object passed to the second parameter contains a code property to distinguish between error types:

传递给第二个参数的对象包含一个用于区分错误类型的code属性:

  • 1 means permission denied

    1表示拒绝权限

  • 2 means position unavailable

    2表示位置不可用

  • 3 means timeout

    3表示超时

添加更多选项 (Adding more options)

When I talked about errors previously, I mentioned the timeout error. Looking up the position can take some time and we can set a maximum time allowed to perform the operation, as an option.

当我以前谈论错误时,我提到了超时错误。 查找位置可能需要一些时间,我们可以选择设置执行操作所允许的最长时间。

You can add a timeout by adding a third parameter to the methods getCurrentPosition() and watchPosition(), an object.

您可以通过向对象的getCurrentPosition()watchPosition()方法中添加第三个参数来添加超时。

navigator.geolocation.getCurrentPosition(position => {  console.log(position)}, error => {	console.error(error)}, {})

Inside this object we can pass the properties

在此对象内,我们可以传递属性

  • timeout to set the number of milliseconds before the request errors out

    timeout设置请求错误超时之前的毫秒数

  • maximumAge to set the maximum “age” of the position cached by the browser. We don’t accept one older than the set amount of milliseconds

    maximumAge设置浏览器缓存的位置的最大“年龄”。 我们不接受超过设定的毫秒数的时间

  • enableHighAccuracy a boolean by default false, requires a position with the highest level of accuracy possible (which might take more time and more power)

    enableHighAccuracy默认为false的布尔值,它要求一个可能具有最高准确度的位置(这可能需要更多时间和更多功能)

Example usage:

用法示例:

navigator.geolocation.getCurrentPosition(position => {  console.log(position)}, error => {	console.error(error)}, {  timeout: 1000,  maximumAge: 10000,  enableHighAccuracy: true})

翻译自:

地理位置api

转载地址:http://yhqgb.baihongyu.com/

你可能感兴趣的文章
[控件] ChangeColorLabel
查看>>
将位图导入为ArcGIS面要素
查看>>
前自增和后自增的区别
查看>>
Linux 基本操作
查看>>
ManagementClass("Win32_Share")之共享目录
查看>>
利用php制作对战后台程序
查看>>
【Leetcode】【Easy】Remove Linked List Elements
查看>>
django 反向解析
查看>>
快速排序一(划分)
查看>>
Oracle面试问题汇总
查看>>
Java程序员必知的8大排序
查看>>
数据库访问性能优化(二)
查看>>
Java-堆排序
查看>>
URI跳转方式地图导航的代码实践
查看>>
python 类私有化
查看>>
clion 快捷键
查看>>
php运算符
查看>>
垂直方向兼容显示的内容多少的情况样式Flex布局
查看>>
CEC Benchmark Functions
查看>>
Count Color poj 2777
查看>>