HTML5 Geolocation location API usage tutorial, html5geolocation
As handheld devices are so common today, location information is extremely important for applications. taxi hailing applications can call nearby vehicles based on users' location information, the Group Buying software can recommend nearby cinemas and foods based on the current location. The 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 apps.
To adapt to this trend, HTML5 provides us with a Geolocation library that allows us to easily implement these features in Web applications. So today I will introduce you to 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:
As shown in the figure, the Geolocation class has three common methods:
1. getCurrentPosition: used to obtain the current position information
2. watchPosition: used to monitor location information in real time when location changes
3. clearWatch: cancels ongoing monitoring operations
Let's take a look at the getCurrentPosition method. below is its function signature:
Copy the content to the clipboard using JavaScript Code
- Navigator. geolocation. getCurrentPosition (success [, error [, options]);
The first parameter is used to specify a successful processing function, the second parameter is used to specify an error processing function, and the third parameter is used to provide some optional configuration items for the function. Now let's call this function:
Copy the content to the clipboard using 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
- });
Once the code is run, a confirmation box is displayed in the browser window, requesting the user to authorize location positioning:
If you click Allow to Allow the site to locate the location, this function starts to obtain the location information from the device, trigger a successful callback function, and pass the location information object to the callback function, in the above Code, we printed the position on the console. The console information is as follows:
As you can see, position is actually an instance of a Geoposition object, which includes the coords and timestamp attributes. The latter is a timestamp, which records the time when the location is obtained, coords contains many location-related information:
Accuracy: The precision range of the location, in meters.
Altitude: the altitude, in meters. If the device does not support height sensing, this attribute is null.
AltitudeAccuracy: the range of altitude accuracy, in meters. If the device does not support height sensing, this attribute is null.
Speed: the speed at which the device moves. The unit is meter/second. If the device cannot provide the speed information, this attribute is null.
Heading: the direction of the current movement. It is represented by a number. The unit is the angle. The clockwise [0,360) degree indicates the angle deviation from the positive north. 0 indicates the positive north. 90 degrees indicates the positive east, 180 degrees indicates the positive and south directions, and 270 indicates the positive and West directions. Note that if speed is 0, heading will be NaN. If the device cannot provide direction information, this property is null.
Longpolling: longitude information
Latitude: latitude Information
We receive this information in the successful callback function, and can obtain the corresponding information based on the actual device and Application Scenario for further operations.
Return to the confirmation box. If we click Block to prevent the site from obtaining the current location information, the code will fail to be authorized. Accordingly, the failed callback function will be triggered, the error object will also be passed in the callback function. Our print information is as follows:
The error parameter is a PositionError instance, which contains an error code and message, indicating the error type and error message respectively. The error code includes the following types:
1: PERMISSION_DENIED-the user rejects the authorization request and fails to authorize
2: POSITION_UNAVAILABLE-location acquisition failed due to some internal errors
3: TIMEOUT-TIMEOUT. The location information has not been obtained after the configured TIMEOUT time.
The above is the failed callback function. When an error occurs during location retrieval, We need to capture it in time and perform corresponding processing operations to get a good user experience. This is very important.
In the above call, We also passed in the third parameter, a simple object, which contains several configuration information, which are used to configure the function running parameters:
EnableHighAccuracy: The default value is false. If it is set to true, it indicates that the device can obtain data with high precision as much as possible, but this will consume a certain amount of time and power.
Timeout: used to specify a time-out period in milliseconds. It indicates that the operation is stopped after the time-out period. The default value is Infinity, indicating that the operation is stopped until the data is obtained.
MaximumAge: the maximum time used to specify the information of a cache location. During this period, the obtained location is retrieved from the cache, in milliseconds. The default value is 0, indicating that no cache is used, get new data every time
The above is an introduction to the getCurrentPosition method. In some scenarios, such as the route navigation application, we need to obtain the latest location in real time and then plan the latest route for the user, the above method cannot meet the requirements. We need to use the watchPosition method:
Copy the content to the clipboard using JavaScript Code
- WatchId = navigator. geolocation. watchPosition (success [, error [, options]);
The usage of the watchPosition method is similar to that of getCurrentPosition. The difference is that the success function is executed multiple times. Once the latest location data is obtained, the success function is triggered, similar, if the latest data fails to be obtained consecutively, the error function is executed multiple times.
You may notice that the above function signature will return a watchId, which indicates the current watch operation. After the position tracking task is completed, you can use the clearWatch function to clear the watchId:
Copy the content to the clipboard using JavaScript Code
- Navigator. geolocation. clearWatch (watchId );
The preceding three APIs are commonly used in Geolocation. In daily development, we can select an appropriate method based on the actual situation to obtain the user's location information.
Most browsers now support Geolocation. However, to be compatible with earlier browsers, we need to determine their support:
Copy the content to the clipboard using JavaScript Code
- If ('geolocation' in navigator ){
- // Getting usr's position
- } Else {
- // Tips: your position is not available
- }
Finally, we use a simple example to demonstrate how to use Geolocation in development:
Copy the content to the clipboard using JavaScript Code
- Var API = {
- // Get recommended data by current longpolling and latitude
- GetSurroundingRecommendations: function (longpolling, latitude, callback ){
- // Simulate data obtaining from server.
- SetTimeout (function (){
- Var data = [
- {
- // Item
- },
- {
- // Item
- }
- ];
- Callback (data );
- },500 );
- }
- };
- Document. addEventListener ('domainloaded', 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,
- Longpolling = coords. longpolling,
- Latitude = coords. latitude;
- API. getSurroundingRecommendations (longpolling, 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 above Code, we first define a method to obtain recommendation data based on the current location, and then try to obtain the current location after the document is loaded, and investigate this method, retrieving the simulated data is actually in the development environment, and the returned data may be further used for rendering the UI and other operations.
Network Device
The local network information used to estimate your location includes: Information about visible Wi-Fi access points (including signal strength), information about your local router, and the IP address of your computer. The accuracy and coverage of the location service vary depending on the location.
In general, the location accuracy obtained by the HTML5 geographic location function in PC browsers is not high enough. If we use this HTML5 feature to make a city weather forecast, it is more than enough, however, for a map application, the error is too large. However, for HTML5 applications on mobile devices, you can set the enableHighAcuracy parameter to true and call the GPS Positioning of devices to obtain high-precision geographic location information.
Optional
In fact, the getCurrentPosition function also supports the third optional parameter, which is an Option Object. There are three options to set:
Copy the content to the clipboard using JavaScript Code
- Var options = {
- EnableHighAccuracy: false,
- Timeout: 5000,
- MaximumAge: 60000
- }
Timeout indicates the timeout time for obtaining a geographical location (unit: milliseconds, and the time allowed by the user is not included). maximumAge indicates that the device is allowed to read the location from the cache and the cache expiration time, the Unit is milliseconds and is set to 0 to disable cache reading. If the returned time is the cache time, it will be reflected in timestamp.