With handheld devices so pervasive today, location information is extremely important for applications, and taxi apps can call nearby vehicles based on their location information, and group buying software can recommend nearby cinemas and food according to their current location, and map applications can quickly plan to their destinations according to their location. It can be said that location information is indispensable for mobile applications.
To keep up with this trend, HTML5 provides us with the Geolocation library, which we can easily implement in Web applications. So today I'll introduce you to the use of this library.
First, we can get an instance of the object from the browser navigator
through the geolocation
property Geolocation
, as shown in:
As we can see in the figure, the Geolocation
classes have three common methods, namely:
getcurrentposition: Used to get the current location information
watchposition: For real-time monitoring of location information when position changes
Clearwatch: Canceling a running monitoring operation
Let's take a look getCurrentPosition
at the method, and here is its function signature:
navigator.geolocation.getCurrentPosition(success[, error[, options]]);
The first parameter specifies a successful processing function, the second parameter specifies an error handler, and the third is used to provide some optional configuration items to the function. Now we're going to call this function:
navigator.geolocation.getcurrentposition (function (position) { Span class= "hljs-comment" >//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 this code runs, the browser window pops up a confirmation box asking the user to authorize location:
If we click allow
to let the site locate, the function starts getting location information from the device and triggering successful
callback function, and the location information object into the callback function, the above code we printed in the console position
, the console information is as follows:
You can see, position The
is actually an instance of a geoposition
object, including coords
and timestamp
two properties, which is a timestamp, When a record gets to the location, coords
contains a lot of information about the location:
Accuracy : The accuracy range of the position, in m
altitude : altitude, in units of m
If the device does not support height sensing, this property is null
altitudeaccuracy : Elevation accuracy range in meters
If the device does not support height sensing, this property is null
speed : The device moves at a rate of m/s
, if the device does not provide speed information, The property is null
heading : The current direction of movement, expressed as a number, in angle
, at clockwise [0, 360) degrees from the angle of the north, 0 for North, 90 degrees for east, 180 for South, 270 for due west direction; note that if speed
is 0
, heading
will be NaN
If the device cannot provide orientation information, this property is null
Longitude : Longitude information
latitude : Latitude information
We receive this information in the successful callback function, which can be used to obtain the corresponding information according to the actual device and the application scenario, and to do further operation.
Back to the confirmation box, if we click to Block
block the site to get the current location information, the code will be authorized to fail, 失败
the corresponding callback function will be triggered, the error
Error object will also be passed to the callback function, our printing information is as follows:
You can see that the error
parameter is an PositionError
instance that contains an error code code
and message
that represents the type of error and the error message, where there are several error codes:
1: permission_denied-User denied authorization request, authorization failed
2: position_unavailable-Location acquisition failure due to some internal error
3: timeout-Timeout, the location information has not been obtained after the configured timeout period has been exceeded
The above is 失败
the callback function, generally get location error, we have to capture in time, and do the appropriate processing operations to obtain a good user experience, it is very important.
In the above call, we also passed the third parameter, a simple object containing several configuration information, which are used to configure the function parameters:
enablehighaccuracy: The default value is false
, if specified true
, to obtain high-precision data when the device is supported, but it consumes a certain amount of time and power
Timeout: Used to specify a time-out, 毫秒
in units, that represents the action taken at the stop location after a time-out, and the default value is Infinity
to stop the operation until the data has been fetched
maximumage: The maximum time to specify a cache location information, in which the location is taken from the cache, in the 毫秒
default value, which means that the 0
cache is not used and the new data is fetched every time.
The above is an getCurrentPosition
introduction to the method, in some scenarios, such as the route navigation application, we need to get the latest position in real-time, and then for the user to plan the latest route, at this time, the above method has not been well satisfied with the requirements, we need to use the watchPosition
method:
watchId = navigator.geolocation.watchPosition(success[, error[, options]]);
watchPosition
Methods are used in a similar way, the function getCurrentPosition
success
executes multiple times, and once the latest location data is obtained, the success
function is triggered, similarly, if the last data is continuously fetched, the error
function is executed multiple times.
You might notice that in the function signature above, it will return one watchId
, which indicates the current watch operation, and when our position tracking task is complete, you can use the clearWatch
function to watchId
clear it:
navigator.geolocation.clearWatch(watchId);
The above is Geolocation
the common three API, daily development we can choose the appropriate method according to the actual situation, and then obtain the user's location information.
Most browsers are now supported Geolocation
, but in order to be compatible with a lower version of the browser, we need to determine its support:
if (‘geolocation‘in navigator) { // getting usr‘s positionelse { // tips: your position is not available}
Finally, we use a simple example to illustrate how it is used in development Geolocation
:
varAPI = {//get recommended Data by current longitude and latitudeGetsurroundingrecommendations: function(longitude, latitude, callback) { //simulate data obtaining from server.SetTimeout ( function() { vardata = [{//item}, {//item} ]; callback (data); }, -); }};d Ocument.addeventlistener (' domcontentloaded ', function() { //detect If geolocation is supported if(!' geolocation ' inchNavigator) {Console.log (' geolocation is not supported in your browser ');return; }varSuccesshandler = function(position) { varcoords = 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: the, Maximumage:0}; Navigator.geolocation.getCurrentPosition (Successhandler, ErrorHandler, Options);},false);
In the above code, we first define a method to obtain the recommended data based on the current location, and then after the document is loaded, we start to try to get the current position, and investigate this method to get the simulated data, it is really in the development environment, may further take advantage of the returned data for rendering UI and other operations.
Geolocation
the introduction on the first here, thank you.
The geolocation of new characteristics of HTML5