HTML5 geolocation Building geo-location-based WEB applications

Source: Internet
Author: User
Tags cos sin

What's new in HTML5

HTML5 is the latest generation of HTML specifications, is the result of the cooperation between the WHATWG and the new, and is still outside the development. Since the last generation of the Html4,web world has undergone great changes, HTML5 's arrival has greatly promoted the development of the WEB, HTML5 provides a lot of new features, mainly:

    • New HTML elements, such as section, Nav, header, footer, article, etc.
    • Canvas Elements for painting
    • Video and audio elements for multimedia playback
    • Geolocation API for positioning
    • Local Storage and offline applications
    • Web Workers API

This paper mainly explains the geolocation function of HTML5 for positioning, and provides an example to introduce its application in practice.

Location information

In HTML5, when a location information is requested, the browser returns the location information if the user consents, which is provided to the browser through the underlying device that supports geolocation, such as a laptop or mobile phone. Location information consists of latitude, longitude coordinates, and some other metadata. For example, the location information of Beijing Imperial Palace consists of a pair of latitude and longitude coordinates: Latitude: North latitude 39.9, Longitude: longitude 116.4.

There are two representations of latitude coordinates: decimal format (for example, 39.9) and DMS (degree Minute Second, angle) format (for example, 39°54′20″). The coordinate format returned by the HTML5 geolocation API is in decimal format. In addition to latitude and longitude coordinates, the HTML5 geolocation also provides positional coordinates for accuracy. In addition, it provides additional metadata, such as altitude, altitude accuracy, driving direction, and speed, depending on the hardware device on which the browser resides.

Location information is generally obtained from the following data sources:

    • IP Address
    • Three-dimensional coordinates
      • GPS (Global Positioning System, positioning systems)
      • Wi-Fi
      • Cell Phone Signal
    • User-definable data

They have advantages and disadvantages as shown in table 1, many devices use multiple combinations of data sources to ensure higher accuracy.

Table 1. Comparison of location information acquisition methods
Data Source Advantages Disadvantages
IP Address Available Anywhere
Processing on the server side
Imprecise (often error, usually accurate to city level)
High computational cost
Gps Very precise. Long positioning time and high power consumption
Poor indoor effect
Additional Hardware Device support required
Wi-Fi Accurate
can be used indoors
Simple, fast
In rural areas where these Wi-Fi access points are low, they cannot be used
Cell Phone Signal Fairly accurate
can be used indoors
Simple, fast
Need to be able to access the phone or its modem device
User definable Get more accurate location data than the program location service
User input may be faster than automatic detection
may be inaccurate, especially if the user's location is changed

Browser support Scenarios

Each browser has a different level of support for HTML5 geolocation and is constantly being updated. The good news: among all the functions of HTML5, HTML5 Geolocation is one of the first to be fully accepted and implemented, and the relevant specifications have reached a very mature stage and are unlikely to make much of a change. As shown in table 2, many browsers already support HTML5 geolocation:

Table 2. Browser support for HTML5 geolocation
Browser Support Situation
Firefox Support for version 3.5 and above
Chrome Supported in the 2nd edition of Chrome with Gears
Internet Explorer Support via Gears plugin
Opera Supported in version 10
Safari Supported in version 4 for use on IPhone

Because the browser supports it differently, it is a good idea to check whether the browser supports the HTML5 geolocation API before using it. Later, you'll see how to check if the browser supports this feature. All of the sample programs in this article ran a successful test on Firefox 12.0.

Privacy

The HTML5 geolocation specification provides a set of mechanisms to protect user privacy. You must obtain explicit permission from the user before you can get the location information of the user. However, as you can see from the accessible HTML5 geolocation application sample, users are often encouraged to share this information. For example, when it's time for lunch, if the app lets users know about the specials of nearby restaurants and their prices and comments, users will find it acceptable to share their location information.

Access to pages that use the HTML5 geolocation API triggers a privacy protection mechanism. Figure 1 shows the page that triggered the privacy protection mechanism in Firefox 12.0.

Figure 1. HTML5 geolocation triggers privacy protection in Firefox 12.0

Because location data is sensitive information, it must be handled, stored, and re-transmitted carefully after it is received. If the user does not have authorization to store the data, the application should delete it immediately after the corresponding task has completed. If you want to retransmit location data, it is recommended to encrypt it.

HTML5 geolocation API

This section details how the HTML5 geolocation API is used.

Browser support Check

Before calling the HTML5 geolocation API function, you need to make sure that the browser supports this feature. When the browser is not supported, you can provide alternative text that prompts the user to upgrade the browser or install plug-ins (such as Gears) to enhance existing browser functionality. Listing 1 is a way of browser support checking.

Listing 1. Check browser support
function Testsupport () {     if (navigator.geolocation) {         document.getElementById ("Support"). InnerHTML = "Supported HTML5 geolocation. ";     } else {     document.getElementById ("Support"). InnerHTML =     "HTML5 geolocation is not supported on this browser! It is recommended that you upgrade your browser or install plugins (such as Gears). ";     }  }

In Listing 1, the Testsupport () function detects the browser's support situation. This function should be called when the page is loaded, if the browser supports HTML5 Geolocation,navigator.geolocation call will return the object, otherwise it will trigger an error. The pre-defined support element displays information about the browser's supported status based on the test results.

Location request

In the HTML5 geolocation feature, there are two types of location requests:

    • One-time location request
    • Recurring Location Update Requests

One-time location request

In many applications, only a single user location can be retrieved or requested. For example, as mentioned earlier, it is time to check the restaurant's specialties and their prices and comments, using the HTML5 geolocation API shown in Listing 2.

Listing 2. Word Location Request API
void GetCurrentPosition (updateLocation, optional handlelocationerror, optional options);

This function accepts a required parameter and two optional parameters.

  • The required parameter updateLocation the function that should be called when the browser indicates that location data is available. The get location operation may take a long time to complete, and the user does not want the browser to be locked when retrieving the location, which is where the data is processed when the actual location information is received asynchronously. It also acts as a function that accepts only one parameter: the Position object position. This object contains coordinates (coords) and a timestamp when acquiring the location data, and many important location data are included in the coords, such as:
      • Latitude (latitude)
      • Longitude (longitude)
      • Accuracy (accuracy)

    Undoubtedly, these three data are the most important location data. Latitude and longitude contain the decimal user location measured by the HTML5 geolocation service. Accuracy the difference between the latitude and longitude values and the actual positions in M. Limited to the implementation of the HTML5 geolocation, the position can only be a rough approximation. Be sure to check the accuracy of the return value before rendering the return value. If the recommended "nearby" restaurant is actually costing users a few hours, it's not good.

    The coordinates may also contain additional data that cannot be guaranteed to be supported by the browser, or null if not supported:

      • altitude– altitude, measured in m;
      • altitudeaccuracy– altitude accuracy, in m units;
      • heading– the direction of travel, relative to the north;
      • speed– speed, in M/s units.

    Listing 3 shows a common implementation code for the UpdateLocation () function that performs a specific update operation based on the coordinate information: updates the text of the three spatial elements on the HTML page, respectively, with the obtained location information.

    Listing 3. Example of using the UpdateLocation () function
     function updateLocation (position) {var latitude = position.coords.latitude;     var longitude = position.coords.longitude;     var accuracy = position.coords.accuracy;     document.getElementById ("latitude"). InnerHTML = latitude;     document.getElementById ("Longitude"). InnerHTML = longitude;  document.getElementById ("accuracy"). InnerHTML = accuracy + "M"; }
  • The
  • optional parameter handlelocationerror indicates the error handler for the browser. Location Information requests may fail because of some uncontrolled factors, and you need to provide an explanation of the user in this function. Fortunately, the API already defines the error numbers for all the error conditions that need to be handled. The error number code is set in the Error object, and the error object is passed as the error parameter to the fault handler. These error numbers are:
    • unknown_error (0): Errors not included in other error numbers, you need to find the details of the error through the message parameter.
    • permission_denied (1): The user denies the browser access to its location information.
    • position_unvailable (2): Failed to attempt to obtain user information.
    • Timeout (3): A timeout value was set in the options object to attempt to get the user location timeout.

    In these cases, you can tell the user what is wrong with the application running, as shown in Listing 4.

    Listing 4. Use error handling function
     function Handlelocationerror (error) {switch (error.code) {case 0:UPDA         Testatus ("An error occurred while trying to get your location information:" + error.message);     Break Case 1:updatestatus ("The user denied obtaining a location information request.")         ”);     Break Case 2:updatestatus ("The browser cannot get your location information.")         ”);     Break Case 3:updatestatus ("Get your location information timed out.         ”);     Break }  }
  • The optional Parameters Options object allows you to adjust the way data is collected by the HTML5 geolocation service. The object has three optional parameters:
    • Enablehighaccuracy: If this parameter is started, the browser will start the high accuracy mode of the HTML5 geolocation service, which will cause the machine to spend more time and resources to determine the location and should be used with caution. The default value is false;
    • Timeout: The unit is MS, telling the browser to get the maximum time allowed for the current location information. If it is not completed within this time period, the error handler is called. The default value is Infinity, which is infinity (unlimited);
    • Maximumage: In MS, the time interval at which the browser retrieves location information. The default value is 0, which means that the location must be recalculated immediately by the browser on each request.

    Use the optional parameters options to update our location request with an optional parameter represented by the JSON object, as follows:

    Listing 5. Update location request with options
    Navigator.geolocation.getCurrentPosition (UpdateLocation, Handlelocationerror,  {timeout:10000});

    This call tells HTML5 geolocation that the error code should be 3 when the processing time of the acquisition location request exceeds 10s (10000ms).

Recurring Location Update Requests

Sometimes it is not enough to get the user's location information only once. For example, the user is moving, as the user moves, the page should be able to constantly update the display of nearby restaurant information, so that the displayed restaurant information is meaningful to the user. Fortunately, the designer of the HTML5 geolocation service has taken this into account, and the application can use the following APIs for repetitive location update requests, and the HTML5 geolocation service will regain access to the user's location when the user's location is changed. and call the UpdateLocation () function to process the new data and notify the user in a timely manner.

Listing 6. Recurring Location Update Request API
void Watchposition (updateLocation, optional handlelocationerror, optional options);

The parameters of this function are the same as the parameters of the GetCurrentPosition function mentioned earlier, and are no longer cumbersome to introduce.

It is also easy to turn off updates, and you only need to use the Clearwatch () function If your application does not need to receive the user's location update messages. Refer to the example given in Listing 7.

Listing 7. Use of watchposition and Clearwatch
var Watchid = navigator.geolocation.watchPosition (updateLocation, handlelocationerror);  Implement some features based on the location information of the continuous update ...//stop receive Location update message navigator.geolocation.clearWatch (WATCHID);
Building Practical applications

This section describes how to build a simple and useful Web application using the recurring location update request that you just introduced: the distance tracker. This application provides insight into the power of the HTML5 geolocation API.

To quickly determine the distance traveled within a certain period of time, a professional device such as a GPS navigation system or pedometer is often used. Based on the powerful services provided by HTML5 Geolocation, we can create a webpage ourselves to track the distance from where the page is loaded to where it is currently located. While it's not very practical on desktops, it's ideal for running on your phone. As soon as you open the sample page in your phone browser and grant access to its location, the application updates the distance that the calculation passes every few seconds. As shown in 2.

Figure 2. HTML5 geolocation sample application running interface on Moto ME525

The Watchposition () function used in this instance has just been described in the previous section. Whenever a new location is returned, it is compared to the last saved location to calculate the distance. The distance calculation is achieved using the well-known haversine formula, which calculates the distance between two points on the Earth according to latitude and longitude. Its JavaScript implementation is shown in Listing 8:

Listing 8. JavaScript implementation of Haversine formula
function Toradians (degree) {     return this * math.pi/180;  }  function distance (latitude1, Longitude1, Latitude2, longitude2) {     //R is the Earth's radius (KM)    var R = 6371;     var deltalatitude = Toradians (latitude2-latitude1);     var deltalongitude = Toradians (longitude2-longitude1);     Latitude1 = Toradians (latitude1);     Latitude2 = Toradians (latitude2);     var a = Math.sin (DELTALATITUDE/2) *             Math.sin (DELTALATITUDE/2) +             Math.Cos (latitude1) *             Math.Cos ( LATITUDE2) *             Math.sin (DELTALONGITUDE/2) *             Math.sin (DELTALONGITUDE/2);     var c = 2 * MATH.ATAN2 (MATH.SQRT (a), math.sqrt (1-a));     var d = R * C;     return D;  }

where the distance () function is used to calculate the distance between two latitude and longitude representations, we can periodically check the user's location and call this function to get the approximate moving distance of the user. There is a hypothesis that the user is moving in a straight line on each interval.

Displaying inaccurate location information will mislead the user, giving the user an extremely bad impression that our application is unreliable and we should try to avoid it. Therefore, we will filter out all the low-precision locations by position.coords.accuracy to update the data. As shown in Listing 9:

Listing 9. Filter inaccurate locations to update data
If the value of accuracy is too large, we consider it inaccurate to calculate the distance if (accuracy >=) {     UpdateStatus ("This data is too unreliable and requires more accurate data to calculate the moving distance.") ");     return;  }

Finally, let's calculate the moving distance. Assuming that at least one of the exact locations has been received before, we will update the total traveled distance and display it to the user, while also storing the current data for later comparisons. The code is shown in Listing 10:

Listing 10. Calculate moving distance
Calculate the move Distance if ((Lastlat! = null) && (Lastlong! = null)) {     var currentdistance = distance (latitude, longitude, l Astlat, Lastlong);     document.getElementById ("This move Distance"). InnerHTML =         "This move Distance:" + currentdistance.tofixed (4) + "km";     Totaldistance + = currentdistance;     document.getElementById ("Total move Distance"). InnerHTML =         "Total travel distance:" + currentdistance.tofixed (4) + "km";     }     Lastlat = latitude;     Lastlong = longitude;     UpdateStatus ("calculated mobile distance succeeded. ");  }

At this point, all the core code for the example has been given (please download the full code from the attachment). With this short 150 lines of HTML and scripting code, we've built a sample application that continuously monitors changes in user locations, demonstrating the use of the geolocation API in almost complete terms. It's fun to put it on your mobile phone or mobile device that supports geolocation, and see how many times you can walk around in a day.

Original address

HTML5 geolocation Building geo-location-based WEB applications

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.