HTML5 Geolocation location API usage tutorial, html5geolocation

Source: Internet
Author: User

HTML5 Geolocation location API usage tutorial, html5geolocation

Geolocation is one of the important features of HTML5. It provides the ability to determine the user location. With this feature, you can develop location-based applications, this article introduces how to use the Geolocation location API of HTML5.
 

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:
 

  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:

 

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:
 

if ('geolocation' in navigator) {   2.  // getting usr's position   3.} else {   4.  // tips: your position is not available   5.}  

 

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.