HTML5 Geolocation location API usage tutorial, html5geolocation

Source: Internet
Author: User

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
  1. 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
  1. Navigator. geolocation. getCurrentPosition (function (position ){
  2. // Success handler code goes here
  3. Console. log (position );
  4. }, Function (error ){
  5. // Error handler code goes here
  6. Console. log (error );
  7. }, {// Options
  8. EnableHighAccuracy: true,
  9. Timeout: 5000,
  10. MaximumAge: 0
  11. });

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
  1. 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
  1. 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
  1. If ('geolocation' in navigator ){
  2. // Getting usr's position
  3. } Else {
  4. // Tips: your position is not available
  5. }

Finally, we use a simple example to demonstrate how to use Geolocation in development:

Copy the content to the clipboard using JavaScript Code
  1. Var API = {
  2. // Get recommended data by current longpolling and latitude
  3. GetSurroundingRecommendations: function (longpolling, latitude, callback ){
  4. // Simulate data obtaining from server.
  5. SetTimeout (function (){
  6. Var data = [
  7. {
  8. // Item
  9. },
  10. {
  11. // Item
  12. }
  13. ];
  14. Callback (data );
  15. },500 );
  16. }
  17. };
  18. Document. addEventListener ('domainloaded', function (){
  19. // Detect if Geolocation is supported
  20. If (! 'Geolocation' in navigator ){
  21. Console. log ('geolocation is not supported in your browser ');
  22. Return;
  23. }
  24. Var successHandler = function (position ){
  25. Var coords = position. coords,
  26. Longpolling = coords. longpolling,
  27. Latitude = coords. latitude;
  28. API. getSurroundingRecommendations (longpolling, latitude, function (data ){
  29. Console. log (data );
  30. });
  31. },
  32. ErrorHandler = function (error ){
  33. Console. log (error. code, error. message );
  34. },
  35. Options = {
  36. EnableHighAccuracy: true,
  37. Timeout: 5000,
  38. MaximumAge: 0
  39. };
  40. Navigator. geolocation. getCurrentPosition (successHandler, errorHandler, options );
  41. }, 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
  1. Var options = {
  2. EnableHighAccuracy: false,
  3. Timeout: 5000,
  4. MaximumAge: 60000
  5. }

 
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.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.