HTML5 New Feature Series: Geolocation
2016-05-10 11:04
417 查看
Today handheld devices are so popularly spreading over our around, and the position feature plays an vital role in the applications developed for these devices. Some applications, such as Uber, can find the nearest car for you by your current position, and the group-buying application can recommend the nearby theaters and food for you via your position information, also, map application can make an optimal road map for you by your current position and help you get to the destination, we can say that, position information is definitely essential for mobile application.
And to follow this trend, HTML5 provides us the Geolocation library, with this feature we are able to build an application in which we can easily implement the functionalities that we mentioned above. Then today I will show you the whole landscape of this feature.
First of all, we can obtain a
And there are three common-used methods below showing:
getCurrentPosition: to get current position
watchPosition: to trace position changes
clearWatch: cancel the watch operation above
We will take a look at the
The first parameter is a success handler, and the second is error handler, the third one is an optional configure for function’s running. Now we attempt to call this function:
Once the code is running, there will be a confirm dialog coming out to request the permission for locating:
If we click
We can see that
accuracy: the accuracy measured in meters
altitude: the altitude measured in meters, if no height sensor provides data for browser, this value will be
altitudeAccuracy: the altitude accuracy measured in meters, likewise, this property will be set to
speed: the speed of device’s moving, measured in
heading: the current moving direction, measured in degrees, [0 ,360), indicates how far off from true north by clockwise, 0 represents true north, 90 is true east, and 180 indicates true south, 270 means true west. Note that if
longitude: longitude expressed in decimal
latitude: latitude expressed in decimal
We will receive these data in success handler, and do next processing according to actual device and application scenario.
Go back to previous confirm dialog, if we click the
We can see that
1: PERMISSION_DENIED - failed to request permission due to user’s rejection
2: POSITION_UNAVAILABLE - failed to get position caused by an internal error
3: TIMEOUT - didn’t get position data after running out the time we configured
That’s the error handler above, commonly if an error occurred when getting position, we need to capture it and handle with it properly to get better experience, it’s very important.
In the invocation of
enableHighAccuracy: by default, it’s a
timeout: the timeout measured in milliseconds, indicates to stop the operation after running out the time, the default is
maximumAge: to specify a longest time to cache the position data, during this period, it will obtain the data from cache when attempting to get position, it’s measured in milliseconds.
Above is all about
We may notice that a
That’s the introduction of the common-used three APIs regarding
Although
At last we will illustrate how it works in real development with a simple program:
In the code, we firstly define a method to get the recommended data by user’s position, and then after the DOM is loaded, we start to get current position data and call this method to obtain mock data, note that, we will do further operations with the data in real development.
That’s all about it, thanks.
And to follow this trend, HTML5 provides us the Geolocation library, with this feature we are able to build an application in which we can easily implement the functionalities that we mentioned above. Then today I will show you the whole landscape of this feature.
First of all, we can obtain a
Geolocationinstance via
geolocationproperty of
navigator:
And there are three common-used methods below showing:
getCurrentPosition: to get current position
watchPosition: to trace position changes
clearWatch: cancel the watch operation above
We will take a look at the
getCurrentPositionmethod in the first place, the following is its signature:
navigator.geolocation.getCurrentPosition(success[, error[, options]]);
The first parameter is a success handler, and the second is error handler, the third one is an optional configure for function’s running. Now we attempt to call this function:
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 });
Once the code is running, there will be a confirm dialog coming out to request the permission for locating:
If we click
Allowbutton, that means we permit the program to locate, and success handler will be triggered after the position information is returned, we printed the
positionin the console:
We can see that
positionis actually a
Geopositioninstance which contains
coordsand
timestamptwo properties, and the latter is a timestamp when position data is obtained, also, there are several position relevant properties included in
coords:
accuracy: the accuracy measured in meters
altitude: the altitude measured in meters, if no height sensor provides data for browser, this value will be
null
altitudeAccuracy: the altitude accuracy measured in meters, likewise, this property will be set to
nullif no height data provided
speed: the speed of device’s moving, measured in
m/s, if no data can get from device, this value will be
null
heading: the current moving direction, measured in degrees, [0 ,360), indicates how far off from true north by clockwise, 0 represents true north, 90 is true east, and 180 indicates true south, 270 means true west. Note that if
speedis
0,
headingwill be
NaN, and if device is not able to provide direction data, this property value will be
null
longitude: longitude expressed in decimal
latitude: latitude expressed in decimal
We will receive these data in success handler, and do next processing according to actual device and application scenario.
Go back to previous confirm dialog, if we click the
Block, it will fail to request permission, accordingly, the error handler will be invoked, and an
errorobject will be passed in this handler, the following is the error object we printed in console:
We can see that
erroris an instance of
PositionError, it contains
codeand
messageproperties, representing error type and error message separately, thereinto, three error types are included:
1: PERMISSION_DENIED - failed to request permission due to user’s rejection
2: POSITION_UNAVAILABLE - failed to get position caused by an internal error
3: TIMEOUT - didn’t get position data after running out the time we configured
That’s the error handler above, commonly if an error occurred when getting position, we need to capture it and handle with it properly to get better experience, it’s very important.
In the invocation of
getCurrentPosition, we also provide the third parameter, just a simple object which contains a few of configurations, they are specified to config the runtime arguments for this function:
enableHighAccuracy: by default, it’s a
falsevalue, and if specified as
true, that means it’s required to get the data as accurate as it can under the condition of supported by device, but it will lead to certain consumption in battery and time.
timeout: the timeout measured in milliseconds, indicates to stop the operation after running out the time, the default is
Infinity
maximumAge: to specify a longest time to cache the position data, during this period, it will obtain the data from cache when attempting to get position, it’s measured in milliseconds.
Above is all about
getCurrentPosition, in some cases such as map navigation, we need the latest position to plan a new road map for user, and apparently getting data once is not able to meet our requirement, therefore, we need the
watchPositionmethod:
watchId = navigator.geolocation.watchPosition(success[, error[, options]]);
watchPositionmethod is similar with
getCurrentPosition, the only difference is that
successwill be running repeatedly, once got the latest data,
successwill be triggered again, similarly, the
errorwill also execute repeatedly if it failed to get up-to-date position serially.
We may notice that a
watchIdis returned in the signature, it indicates the current ID of watch operation, and we can clear this operation by calling the
clearWatchfunction with this
watchIdafter tracing position is done:
navigator.geolocation.clearWatch(watchId);
That’s the introduction of the common-used three APIs regarding
Geolocation, we can choose appropriate method according to the actual situation to get user’s position.
Although
Geolocationhas been supported by the majority of browsers, in order to take care of the browser in low version, we still need to detect if it supports:
if ('geolocation' in navigator) { // getting usr's position } else { // tips: your position is not available }
At last we will illustrate how it works in real development with a simple program:
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);
In the code, we firstly define a method to get the recommended data by user’s position, and then after the DOM is loaded, we start to get current position data and call this method to obtain mock data, note that, we will do further operations with the data in real development.
That’s all about it, thanks.
相关文章推荐
- HTML5移动应用开发最容易踩到的几个坑
- html5 新特性ajax跨域的问题和处理
- HTML5学习之新增标签
- PHP & HTML5 学习大纲
- h5+
- HTML5全局属性(一)
- HTML5 共享进程
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆
- HTML5 canvas 画布画圆