Home > Web Front-end > H5 Tutorial > body text

Detailed explanation of how to use HTML5's Geolocation API

黄舟
Release: 2017-03-15 16:21:50
Original
2544 people have browsed it

Geolocation is one of the important features of HTML5. It provides the function of determining the user's location. With this feature, applications based on location information can be developed. Today this article will introduce it to you. HTML5's GeolocationAPIUsage tutorial.

Today when handheld devices are so common, location information is extremely important for applications. Taxi-hailing applications can use the user's location information Call nearby vehicles, group buying software can recommend nearby theaters and food based on the current location, MAP application can quickly plan the route to the destination based on the user's location, it can be said that location information is indispensable for mobile applications Short.
In order to follow this trend, HTML5 provides us with the Geolocation library, with which we can easily implement the above functions in web applications. So today I will introduce to you the use of this library.

Basic usage
First, we can get a Geolocation instance from the browser's navigator object through the geolocation attribute, As shown in the figure below:
Detailed explanation of how to use HTML5's Geolocation API

We can see in the figure that the Geolocation class has three commonly used methods, they are:

1.getCurrentPosition: Used to obtain the current position information
2.watchPosition: Used to monitor the position information in real time when the position changes
3.clearWatch: Cancel the current position Running monitoring operation
Let’s first take a look at the getCurrentPosition method. The following is its function signature:

navigator.geolocation.getCurrentPosition(success[, error[, options]]);
Copy after login
  1. The first parameter is used to specify a success The second parameter is used to specify an error handling function, and the third parameter is used to provide some optional configuration items to the function. Now let’s call this function:

JavaScript Code复制内容到剪贴板
navigator.geolocation.getCurrentPosition(function(position) {   
    //success handler code goes here   
    console.log(position);   
}, function(error) {   
    //error handler code goes here   
    console.log(error);   
}, {//options   
    enableHighAccuracy: true,   
    timeout: 5000,   
    maximumAge: 0   
});
Copy after login




##Once this code is run, a confirmation box will pop up in the browser window, requesting the user's authorization for location location:


Detailed explanation of how to use HTML5's Geolocation API

If we click

Allow allows the site to perform location positioning. This function starts to obtain location information from the device, triggers a successful callback function, and passes the location information object into the callback function. In the above code, we are controlling Position is printed on the console, and the console information is as follows:
Detailed explanation of how to use HTML5's Geolocation API

You can see that position is actually an instance of a Geoposition object, which includes co

ords and timestamp. An attribute, the latter is a timestamp , recording the time when the location was obtained. Coords contains a lot of location-related information:

accuracy: 位置的精确度范围,单位为米
altitude: 海拔高度,单位为米,如果设备不支持高度感应,则该属性为null
altitudeAccuracy: 海拔精确度范围,单位为米,如果设备不支持高度感应,则该属性为null
speed: 设备移动的速度,单位为米/秒,如果设备不能提供速度信息,该属性为null
heading: 当前移动的方向,以数字表示,单位为角度,以顺时针[0, 360)度表示偏离正北方的角度,0表示正北方向,90度表示正东方向,180度表示正南方向,270表示正西方向;需要注意的是,如果speed为0,则heading会是NaN,如果设备不能提供方向信息,则该属性为null
longitude: 经度信息
latitude: 纬度信息
我们在成功的回调函数中接收到这些信息,可以根据实际的设备和应用场景获取相应的信息,做进一步的操作。
回到刚才的确认框,如果我们点击了Block阻止该站点获取当前的位置信息,代码就会授权失败,相应地,失败的回调函数就会被触发,error错误对象也会被传入回调函数,我们的打印信息如下:
Detailed explanation of how to use HTML5's Geolocation API

可以看到error参数是一个PositionError实例,包含一个错误码code和message,分别表示错误的类型和错误提示消息,其中错误码有以下几种:

1: PERMISSION_DENIED - 用户拒绝了授权请求,授权失败
2: POSITION_UNAVAILABLE - 因为一些内部错误,导致位置获取失败
3: TIMEOUT - 超时,超过了配置的超时时间后还未获取到位置信息
上面就是失败的回调函数,一般获取位置出现错误时,我们都要及时捕获,并做相应的处理操作,以获取好的用户体验,这一点很重要。
在上面的调用中,我们还传入了第三个参数,一个简单的对象,里面包含了几个配置信息,它们都是用来配置函数运行参数的:

enableHighAccuracy: 默认值为false,如果指定为true,则表示在设备支持的情况下,尽可能获取高精准度的数据,但这会在时间和电量方面存在一定的消耗
timeout: 用于指定一个超时时间,单位为毫秒,表示在超时后停止位置获取的操作,默认值是Infinity,表示直到获取到数据后才停止该操作的进行
maximumAge: 用于指定一个缓存位置信息的最长时间,在这个时间段内,获取位置时会从缓存中取,单位为毫秒,默认值为0,表示不使用缓存,每次都取新的数据
上面是关于getCurrentPosition方法的介绍,在某些场景下,例如路线导航应用,我们需要实时地获取最新位置,进而为用户规划最新的路线,这时,上面的方法已经不能很好的满足需求了,我们需要使用watchPosition方法:

watchId = navigator.geolocation.watchPosition(success[, error[, options]]);
Copy after login

watchPosition方法的使用方式和getCurrentPosition类似,不同的是,success函数会执行多次,一旦获取到最新的位置数据,success函数就会被触发,与之相似地,如果连续获取最新的数据失败时,error函数也会被执行多次。
大家或许会注意到,上面的函数签名中,会返回一个watchId,它标示着当前的watch操作,当我们位置跟踪任务完成后,可以使用clearWatch函数将这个watchId清除即可:

navigator.geolocation.clearWatch(watchId);
Copy after login

上面就是Geolocation的常用的三个API,日常开发中我们可根据实际情况选用合适的方法,进而获取用户的位置信息。
现在大部分浏览器都已支持Geolocation了,可是为了兼容低版本的浏览器,我们需要判断它的支持情况:

if ('geolocation' in navigator) {   
  // getting usr's position   
} else {   
  // tips: your position is not available   
}
Copy after login

最后,我们用一个简单的例子来演示在开发中是如何使用Geolocation的:

var API = {   
    //get recommended data by current longitude and latitude   
    getSurroundingRecommendations: function(longitude, latitude, callback) {   
        //simulate data obtaining from server.   
        setTimeout(function() {   
            var data = [   
                {   
                    //item   
                },   
                {   
                    //item   
                }   
            ];   
            callback(data);   
        }, 500);   
    }   
};   
  
document.addEventListener('DOMContentLoaded', function() {   
    //detect if Geolocation is supported   
    if (!'geolocation' in navigator) {   
        console.log('Geolocation is not supported in your browser');   
        return;   
    }   
  
    var successHandler = function(position) {   
        var coords = position.coords,   
            longitude = coords.longitude,   
            latitude = coords.latitude;   
  
        API.getSurroundingRecommendations(longitude, latitude, function(data) {   
            console.log(data);   
        });   
    },   
    errorHandler = function(error) {   
        console.log(error.code, error.message);   
    },   
    options = {   
        enableHighAccuracy: true,   
        timeout: 5000,   
        maximumAge: 0   
    };   
  
    navigator.geolocation.getCurrentPosition(successHandler, errorHandler, options);   
  
}, false);
Copy after login


在上面的代码中,首先我们定义一个根据当前位置获取推荐数据的方法,然后在文档加载完成后,开始试图获取当前位置,并调研这个方法,获取模拟的数据,真是开发环境中,可能会进一步利用返回的数据做渲染UI等操作。

网络设备
位置服务用于估计您所在位置的本地网络信息包括:有关可见 WiFi 接入点的信息(包括信号强度)、有关您本地路由器的信息、您计算机的 IP 地址。位置服务的准确度和覆盖范围因位置不同而异。
总的来说,在PC的浏览器中 HTML5 的地理位置功能获取的位置精度不够高,如果借助这个 HTML5 特性做一个城市天气预报是绰绰有余,但如果是做一个地图应用,那误差还是太大了。不过,如果是移动设备上的 HTML5 应用,可以通过设置 enableHighAcuracy 参数为 true,调用设备的 GPS 定位来获取高精度的地理位置信息。

可选项
事实上,上述getCurrentPosition函数还支持第三个可选的参数,是一个 Option Object,一共有三个选项可以设定:

JavaScript Code复制内容到剪贴板
var options = {     
    enableHighAccuracy: false,     
    timeout: 5000,     
    maximumAge: 60000     
}
Copy after login


 
其中timeout是设定地理位置获取的超时时间(单位为毫秒,用户选择允许的时间不计算在内);而maximumAge表示允许设备从缓存中读取位置,缓存的过期时间,单位是毫秒,设为0来禁用缓存读取。如果返回的是缓存中的时间,会在timestamp中反映出来。
 

The above is the detailed content of Detailed explanation of how to use HTML5's Geolocation API. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!