HTML5 API power

Source: Internet
Author: User
Tags dojo toolkit

So what is API?
Application Programming Interface (API) is a set of programming commands and standards used to access a software application. By using APIs, you can design products driven by the services provided by APIs.
HTML5 has some new APIs, such:
1. A 2D drawing API used with new Canvas elements for rendering graphics or other visual images.
2. An API that supports the caching mechanism of offline web applications.
3. An API for Playing videos and audios, used with new video and audio elements.
4. A history API converts browsing history into accessible, and allows you to add pages to this history.
5. A drag-and-drop API used with the draggable attribute.
6. An editing API used with the contenteditable attribute.
7. Key-value pairs and embedded SQL database client storage, using JavaScript APIs.
This article focuses on two APIs: geolocation and web worker. First, analyze these APIs and create a page that contains these two APIs.
Ubiquitous business: Geolocation
The geolocation API is used to determine and share geographic locations. The API returns longitude and latitude coordinates-this is the information that an enterprise can use to provide services in a region near this coordinate, such services are usually called Location-Based Services (lbs ).
LBs uses geographic data sources as a reference. These geographic data sources are used to identify the physical location of the monitored instrument and identify the persons associated with the location. This feature gives interested parties the opportunity to interact with this person, which is based on some geographically-centered Interest market.
Business is actually to create quality, practicality and value for customers, while also to create economic and financial benefits for stakeholders, creditors, shareholders, employees and suppliers. Location-driven lbs makes it easy to track and monitor a package (or an individual using a non-browser device or browser. From the commercial point of view, geographical location involves the use of geographical assets to determine the location of someone or something, sell this particular set of information to anyone who wants to use it for social, commercial, or other purposes, as long as the information owner's practice is legally permitted.
How geolocation works
Geolocation API is based on a new property of the Global Object navigator. geolocation. This Javascript navigator object provides some useful information about the visitor's browser and system. Geolocation can determine the longitude and latitude of visitors who use IP addresses, web-based databases, wireless network connections, and triangular positioning or GPS technology. It should be noted that the accuracy of the information provided by geolocation will change based on the means for obtaining information. By accident, in some locations, you may not be able to get a clear geographic location reading or a little data.
The script can use navigator. the geolocation object is used to determine the location information related to the user's host device. After the location information is retrieved, a location object is created and filled with the data.
The navigator. geolocation object has three methods:
1. getcurrentposition ()
2. watchposition ()
3. clearwatch ()
Getcurrentposition () method
The getcurrentposition () method is used to retrieve the current user location, but only once. When this method is called by a script, the method asynchronously attempts to obtain the current location of the host device. Asynchronous communication means that the sender and receiver are not added to the communication process at the same time. Using asynchronous communication allows the browser to continue other activities, so that it does not need to wait for the response from the receiving entity.
The getcurrentposition () method can have a maximum of three parameters:
1. geolocationsuccess: Bring back the callback of the current location (required)
2. geolocationerror. Callback used when an error occurs (optional)
3. geolocationoptions. geographic location options (optional)
Navigator. geolocation. the getcurrentpositon () method uses a position object as a parameter to return the current location of the host device to geolocationsuccess. If an error occurs, the geolocationerror callback uses a positionerror object for calling. You can set three attributes of geolocationoptions: enablehighaccuracy, timeout, and maximumage. These optional attributes enable high accuracy. If the device supports this high accuracy, this is the longest wait time for the location to be returned; and the maximum number of times, the cache location can be used within this period of time.
Call the getcurrentposition () method as follows:
Void navigator. geolocation. getcurrentposition (geolocationsuccess, geolocationerror, geolocationoptions );
Watchposition () method
The watchposition () method periodically polls the user's location to check whether the user's location has changed. It can contain up to three parameters.
When watchposition is called, it starts a viewing process asynchronously. This process involves obtaining a new position object and creating a watchid. If this operation is successful, the corresponding geolocationsuccess that uses a position object as the parameter will be called. The operation involved in the failure is to call this method using a non-empty geolocationerror parameter. The watchposition method uses a positionerror object as the parameter to generate geolocationerror. When the device location changes, a suitable callback with a new position object will be called.
The watchposition () method is called as follows:
Long navigator. geolocation. watchposition (geolocationsuccess, geolocationerror, geolocationoptions );
Clearwatch () method
The clearwatch () method terminates the ongoing watchposition (). This method can contain only one parameter. During the call, it finds the previously started watchid parameter and immediately stops it.
Call the clearwatch () method as follows:
Void navigator. geolocation. clearwatch (watchid)
Geolocation data: Position object
The geolocation API returns a location object that has two attributes: Timestamp and coords. The timestamp attribute indicates the creation time of the geographic location data. The coords attribute also contains seven attributes:
1. coords. Latitude: Estimated latitude
2. coords. longpolling: Estimated longitude
3. coords. Altitude: Estimated height
4. coords. Accuracy: accuracy of latitude and longitude estimates in meters
5. coords. altitudeaccuracy: accuracy of the provided height estimates in meters
6. coords. Heading: The angle direction of the current movement of the host device, clockwise relative to the north direction
7. coords. Speed: current local speed of a device in meters per second
Only three of these attributes are guaranteed: coords. Latitude, coords. longpolling, and coords. accuracy. The rest return NULL, depending on the capabilities of the device and its backend locating server. If possible, the heading and speed attributes can be calculated based on the user's previous locations.
Web worker that plays a rescue role
Web worker (web worker thread) can remedy the problems caused by concurrency. web worker is the answer to the single-thread JavaScript question from the HTML5 family: they run the processing process in the thread separate from the home page, and retain the page for main functions, such as maintaining a stable UI.
A web worker is a Javascript file that is loaded and executed in the background. These workers allow you to dynamically load a Javascript file and then run the script using background processes that do not affect the UI. Web worker access is restricted, and only strings can be transmitted. Because web worker does not use the UI thread of the browser, they are not allowed to access the Dom. Workers can use self and this to reference global variables used to access worker (workers can use both self and this references for the worker's Global
Scope), worker communicates with the parent page by using the event model and postmessage () method.
Because web worker has multiple threads, they can only access a subset of JavaScript Functions. web worker can:
1. Access the navigator object
2. Use a read-only location object
3. Execute XMLHttpRequest to send HTTP or HTTPS requests
4. Use setTimeout ()/cleartimeout () and setinterval ()/clearinterval () to set the time or interval
5. Access the application Cache
6. Use the importscripts () method to import external scripts
7. Generate other web worker (subworker must have the same source as the home page and must be placed in the same location as the parent worker .)
There are two types of web worker: dedicated-type worker and shared-type worker.
Dedicated web worker
A dedicated worker is connected with the script used to create it. It can communicate with other worker or browser components, but cannot communicate with Dom.
The creation method of a dedicated worker is to pass a Javascript file name to a new worker instance, and create a new worker by specifying the worker execution script Uri and using the worker () constructor. To create a dedicated worker, enter the following code to create a dedicated worker object:
VaR worker = new worker ('worker. js ');
Shared web worker
Like a dedicated-type worker, a shared-type web worker cannot access Dom, and its access to form attributes is also limited. A shared web worker can only communicate with other shared Web workers in the same domain. It is created by passing a javascript name to a new shared worker instance.
The page script can communicate with the shared web worker, which is different from the dedicated web worker by using a port) object and append it to a message event handler. In addition, before using the first postmessage (), you must call the START () method of the port.
After receiving the first message of the web worker script, the shared web worker attaches an event handler to the active port. Generally, the handler runs its own postmessage () method to return a message to the calling code, and then the START () method of the port generates a valid message process.
To create a shared web worker, you must create a sharedworker object instead of a worker object. The following code creates a sharedworker object:
VaR worker = new sharedworker ('worker. js ');
Construct a page containing the two APIs
You will design a page that contains the basic working modes of the geolocation and web worker API. In addition, you will also use the Google map API to render the data collected as a map.
As shown in organization 1 of the page, it contains a header area created using the Figure 1. API page layout
The <section> and <aside> sections contain APIs. The section area contains the geolocation API, And the aside area contains web worker, which is used to calculate prime numbers.
At execution, the page is displayed as 2. To view geographic location data, you must first agree to share your information. Web worker is started when the page is loaded. If you want to see the prime number, click the display web worker button.
Figure 2. API webpage
HTML file
The HTML file starts with the standard HTML5 information shown in Listing 1. The Listing 1. content at the beginning of the HTML file
<! Doctype HTML>
<HTML>
<Head>
<Title> basic geolocation map & web worker prime number calculator </title>
<SCRIPT src = "http://maps.google.com/maps/api/js? Sensor = false"
Type = "text/JavaScript"> </SCRIPT>
<Link href = "geolocationwebworker.css" rel = "stylesheet" type = "text/CSS">
<SCRIPT src = "HTML-Part3-GeolocationWebWorker.js" type = "text/JavaScript"> </SCRIPT>
</Head>
<Body> the tag contains the onload event, which calls the initialization function of the geographical location, as shown in Listing 2. This function checks whether Geographic Positioning can be used in this browser. This initialization function is placed in a Javascript file. If the browser can communicate with geolocation API, the map will be rendered.
Listing 2. Initializing Geolocation
<Body onload = "initgeoapp ();">
<Header>
<Hgroup>
<H1> geolocation & web worker <H2> making it work </H2>
</Hgroup>
</Header>
The <section> label in listing 3 contains navigator. the output information of the geolocation object. the longitude and latitude returned by the API are used to create a map canvas. The position coords data is also displayed using the <span> </span> label.
Listing 3. Map and location of Geolocation
<Section>
<P> This is the geolocation example map. </P>
<Div id = "map_canvas"> </div>

<P> This is the output from the navigator. geolocation object. </P>
<Table>
<Tr>
<TD> accuracy: </TD>
<TD> <span id = "accuracyoutput"> </span> </TD>
</Tr>
<Tr>
<TD> altitude: </TD>
<TD> <span id = "altitudeoutput"> </span> </TD>
</Tr>
<Tr>
<TD> altitudeaccuracy: </TD>
<TD> <span id = "altitudeaccuracyoutput"> </span> </TD>
</Tr>
<Tr>
<TD> heading: </TD>
<TD> <span id = "headingoutput"> </span> </TD>
</Tr>
<Tr>
<TD> latitude: </TD>
<TD> <span id = "latitudeoutput"> </span> </TD>
</Tr>
<Tr>
<TD> longpolling: </TD>
<TD> <span id = "longitudeoutput"> </span> </TD>
</Tr>
<Tr>
<TD> speed: </TD>
<TD> <span id = "speedoutput"> </span> </TD>
</Tr>
</Table>
</Section>
<Aside>
<P> This is the web worker. </P>
<P> prime number calculation result:
<Output id = "result"> </output> </P>
The web worker calculates the prime number. <output> This new tag is used to display the computing result provided by the web worker, <output> the ID in the tag is the same as the ID used by JavaScript to identify the computation to be executed. The ids used in the <span> and <output> labels make them accessible in the Dom. If no ID is referenced, javaScript does not know which <span> and <output> to use. Listing 4 shows the web worker output.
Listing 4. web worker output
<Aside>
<P> This is the web worker. </P>
<P> prime number calculation result:
<Output id = "result"> </output> </P>
<Input> The onclick used first shows the value calculated by the prime number web worker, and the second onclick is used to stop web worker. Listing 5 provides the code. When the button is clicked, The displayworker () function displays the result calculated by the web worker. The web worker starts to calculate the prime number after loading the page.
Listing 5. web worker input tag
<Input type = "button" value = "display web worker">
<Input type = "button" value = "Stop web worker">
</Aside>
</Body>
</Html>
JavaScript files
Javascript is the engine behind the API displayed on the example Page. geolocation API is initialized by calling the initgeoapp () function, which is determined by onload () in the <body> label () function executed by event: it determines whether your browser can use geographic location data (see Listing 6 ). If your browser can use geographic location data, the geolocation API will be called. If the call is successful, the property value in position will be used to draw the map, and the property value will be printed after the map.
Listing 6. geolocation Functions
Function initgeoapp ()
{
If (navigator. geolocation)
{
Navigator. geolocation. getcurrentposition (success, failure );
}
Else
{
Alert ("your browser does not support geolocation services .");
}
}
Based on the ID provided in the HTML file, document. getelementbyid is used to retrieve the value. Document. getelementbyid is a method of document objects. It should be accessed by using document. getelementbyid, as shown in listing 7. The position attribute values are stored here so that they can be used to print attributes under the map to be rendered.
Listing 7. Use getelementbyid to get the coords Value
VaR map;
Function success (position)
{
Document. getelementbyid ("accuracyoutput"). innerhtml =
Position. coords. accuracy;
Document. getelementbyid ("altitudeoutput"). innerhtml =
Position. coords. aktitude;
Document. getelementbyid ("altitudeaccuracyoutput"). innerhtml =
Position. coords. altitudeaccuracy;
Document. getelementbyid ("headingoutput"). innerhtml =
Position. coords. Heading;
Document. getelementbyid ("latitudeoutput"). innerhtml =
Position. coords. Latitude;
Document. getelementbyid ("longitudeoutput"). innerhtml =
Position. coords. longpolling;
Document. getelementbyid ("speedoutput"). innerhtml =
Position. coords. speed;
The following part defines the coordinates of the latlng object of Google map API, as shown in listing 8. The Google map API latlng object provides the coordinates required for creating a map. You can set the zoom level and several other options to create the appearance of the map presented to you.
Listing 8. Google map options
VaR coordinates = new Google. Maps. latlng (position. coords. Latitude,
Position. coords. longpolling );

VaR myoptions =
{
Zoom: 14,
Center: coordinates,
Maptypecontrol: false,
Navigationcontroloptions: {style: Google. Maps. navigationcontrolstyle. Small },
Maptypeid: Google. Maps. maptypeid. Roadmap
};
Note that the maptypeid option selects roadmap. The map displayed by this option is 2. This option has four optional values:
1. Roadmap
2. Hybrid
3. Satellite
4. Terrain
Figure 3 shows what the web page looks like when you select the hybrid option.
Figure 3. Use the hybrid map API webpage.
Map_canvas is used to create a map. This ID is the <div> ID in the HTML file.
Map = new Google. Maps. Map (document. getelementbyid ("map_canvas"), myoptions );
Put an initial position mark on the map. Listing 9 shows this code.
Listing 9. Placing an initial map tag
VaR marker = new Google. Maps. Marker ({
Position: coordinates,
Map: map,
Title: "You are here ."
});
}

Function failure ()
{
Alert ("sorry, cocould not obtain location ");
}
Web worker starts execution after page initialization. If the user wants to display the output of the executed computing, he/she can click the display web worker button, which will call the displayworker () function. Listing 10 shows its code.
Listing 10. web worker
VaR worker = new worker ('primenumberwebworker. js ');

Function displayworker ()
{
Worker. onmessage = function (Event)
{
Document. getelementbyid ('result'). innerhtml = event. Data;
};
}
If you want to stop a web worker, you can click the stop web worker button to call the stopworker () function in listing 11.
Listing 11. Terminate worker
Function stopworker ()
{
Worker. Terminate ();
}
Web worker File
This file is a web worker of the prime number calculator. It calculates each prime number until it is terminated. Listing 12 shows its code.
Listing 12. Calculating prime numbers
VaR n = 1;
Search: While (true ){
N + = 1;
For (VAR I = 2; I <= math. SQRT (n); I + = 1)
If (N % I = 0)
Continue search;
Postmessage (N );
}
Css3 files
The css3 file in listing 13 provides the format displayed on the HTML5 page.
Listing 13. css3 description
* {Font-family: Arial, Helvetica, sans-serif;
}

Body {
Margin: 0 300px 0 300px;
Color: #990000;
Background-color: # ffffcc;
}

Header> hgroup H1 {
Margin: 0 0 3px 0;
Padding: 0;
Text-align: center;
Font-size: 30px;
}

Header> hgroup H2 {
Margin: 0 0 15px 0;
Padding: 0;
Text-align: center;
Font-style: italic;
Font-size: 12px;
}

Header P {
Margin: 0 0 20px 0;
Padding: 0;
Text-align: center;
Font-size: 12px;
}

Aside {
Width: 200px;
Height: 175px;
Margin:-pixel PX 0 0 pixel PX;
Background-color: #990000;
Padding:. 5px 0 0 10px;
Color: # ffffff;
Font-weight: bold;
}

Div {
Width: 400px;
Height: 250px;
}
Conclusion
This part of the article series studies the practicality of geolocation and web worker APIs. These two APIs are selected because they are put together to demonstrate both innovative API usage and actual availability. Geolocation is a good example for the use of HTML5 specifications in creating a new business model. Similarly, the role of web worker is a solution to some problems inherent in the concurrency of JavaScript.
These two APIs jointly demonstrate a combination of HTML5 use modes for business and society. Therefore, their functions demonstrate the unique convenience and General Management Methods of HTML5 rich Internet applications.
Download
Name size Download Method
Html5apis.zip 10kb HTTP
Instructions on download Methods
Learning Materials
1. The web workers specification published by whatwg provides detailed worker information.
2. geolocation API Level 2 specification, W3C specification for geographic positioning, provides detailed use cases and requirements. This part of content is useful in programming API commercial and social applications.
3. Build Web applications with HTML 5 (developerworks, March 2010) discusses several new features introduced by HTML5.
4. creating mobile Web applications with HTML 5, Part 1: Combine HTML 5, geolocation APIs, and web services to create mobile mashups (developerworks, May 2010) provides valuable insights on developing mobile applications.
5. Create Modern web sites using HTML5 and css3 (developerworks, March 2010) is an HTML5 and css3 article with multiple sections.
6. In the new elements in HTML 5 (developerworks, August 2007) article, you will find some information about several new elements in HTML5.
7. <HTML> the 5doctor website provides a great view of the current trend of HTML5.
8. w3schools.com HTML5 tag reference provides a list of all-encompassing HTML5 tags, definitions, and examples.
9. The whatwg website provides detailed HTML5 specifications.
10. Web development zone is specific to articles covering various web-based solutions.
11. Keep an eye on developerworks's technical events and webcasts.
12. developerworks On-Demand demos: Watch various demos, ranging from product installation and setup for beginners to advanced features provided for experienced developers.
13. Follow developerworks on Twitter.
Obtain products and technologies
Dojo toolkit, an open-source modular JavaScript library, helps you quickly develop cross-platform JavaScript/Ajax-based applications and websites.
Discussion
1. Now create your developerworks profile and set a viewing list for HTML. Establish and maintain contact with the developerworks community.
2. Find other developerworks members interested in Web development.
3. Share your knowledge: Join a developerworks group focusing on Web topics.
4. Roland BARCIA talked about Web 2.0 and middleware in his blog.
5. Follow the shared bookmarks on Web topics of the shortwork member.
6. Quick answer: visit the Web 2.0 apps forum.
7. Quick answer: Visit the Ajax forum.

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.