Saturday, 25 April 2015

Html tutorials session 19

 There are different sources through which devices can determine the information about the location. These are as follows:
GPS - GPS is a satellite navigation system that provides information about the location on any part of the globe. The GPS system is maintained by the government of the United States and is used by modern mobile devices with GPS capability.
IP Address - Location information can be derived from IP Address. The IP Address is assigned to devices, such as desktops, printers, and so on connected on a network.
GSM/CDMA Cell IDs - These are used by the cell phones.
WiFi and Bluetooth MAC address - These are used by devices that have wireless network connection.
User Input - It is a software tool which can be used on any device requesting for location information. The information retrieved by the tool is based on the data provided by the user, such as, a zip code.
19.3 Geolocation API
In HTML5, the Geolocation API is a specification provided by W3C. It provides a consistent way to develop location-aware Web applications.
The Geolocation API provides a high-level interface that can be used by developers to retrieve location information related to the hosting devices. The interface hides the details, such as how the information is gathered or which methods were used to retrieve the information. This helps the developer to concentrate on geographic information rather than its processing methods.
The object that holds implementation of the Geolocation API is the Geolocation object. This object is used in JavaScript to retrieve the geographic information about the devices programmatically. The browser processes the script and returns the location to the Geolocation API.
The Geolocation API is supported on most of the modern browsers available on desktop and mobile phones.
Implementing Geolocation Object
The Goelocation object is available as a new property of the navigator object. The navigator object is a browser object that allows a user to retrieve information about the specific location.
The syntax shows how to create a Geolocation object in JavaScript.
Syntax:
var geolocation = window.navigator.geolocation;
where,
window: Is the top level object in JavaScript object hierarchy
Code Snippet 1 demonstrates the script that tests the existence of Geolocation object within a browser.
Code Snippet 1:


<!DOCTYPE html>
<html>
<head>
<title> Testing Support for Geolocation in Browsers</title>
<script>
function display_location_enabled()
{       
// Default message
var str = “Geolocation is not supported in this browser”;

if (window.navigator.geolocation)
{
str = “Geolocation is supported in this browser”;
}
alert (str);
}
</script>
</head>
<body>
<input type=”button” value=”Geolocation Support”
onClick=”display_location_enabled()”></input>
</body>
</html>    
   
In the code, the if statement checks existence of the geolocation property in the browser. If the browser provides an implementation for the property, then an alert window displays the message ‘Geolocation is supported in this browser’. Otherwise, the default message is displayed.
Figure 19.2 shows the existence of Geolocation object in the Chrome browser



Geolocation Methods
The Geolocation object provides three methods that can be used to determine the current position of the user.


Method     Description       
getCurrentPosition()     Retrieves the current geographic location information of the user       
watchPosition()     Retrieves the geographic information of the device at regular intervals   


HTML5 Geolocation and APIs V 1.1 


Method     Description       
clearWatch()     Terminates the current watch process    
Retrieve User Position
The current position of a user is retrieved using the getCurrentPosition (successCallback, errorCallback, options) method. This function accepts three parameters, out of which two are optional, errorCallback and options.
The first parameter, successCallback is the name of the function which is invoked after the position of a device is found successfully. The second parameter, errorCallback is the name of the function which will be called, if an error occurs in retrieving the position. The last parameter, options represents a PositionOptions object.
Code Snippet 2 demonstrates the markup that will retrieve the current location of the user.

<!DOCTYPE html>
<html >
<head>
<title>Geolocation API</title>
<script>
function getLocation()
{
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
alert (“Geolocation is not supported in this browser.”);
}
}


function showPosition(position)
{
alert(‘Latitude: ‘ + position.coords.latitude + ‘\n’ + ‘Longitude:
‘ + position.coords.longitude);
}
</script>
</head>
<body>
<input type=”button” value=” Display Location”
onClick=”getLocation()”/>
</body>
</html>    


   

In the code, the getCurrentPosition() function obtains the position which is passed as a parameter to the showPosition() function. The showPosition() function obtains the coordinates of a location through position object.
The position object is defined in the Geolocation API and holds the current location of the device. It contains attribute named coords that retrieves the latitude and longitude of the location. The values retrieved for latitude and longitude are in decimal degrees.


Attribute     Description       
coords     An object of type Coordinates that provides different properties, such as latitude, longitude, altitude, accuracy, speed, and so on       
timestamp     An object of type DOMTimeStamp    

Handling Errors
An application could fail in gathering geographic location information. In that case, the Geolocation object calls an errorCallback() function. The errorCallback() function handles errors by obtaining a PositionError object from the API.
PositionError Object
The PositionError object holds information related to errors occurred while finding the geographic location of the user.


Property     Description       
code     Returns a numeric value for the type of error occurred       
message     Returns a detailed message describing the error encountered. The message can be used for debugging    
 
<!DOCTYPE html>
<html>
<head>
<title>Handling Error</title>
<script>
function getLocation()
{
function showPosition(position)
{
alert(‘Latitude: ‘ + position.coords.latitude + ‘\n’ +
‘Longitude: ‘ + position.coords.longitude);
}
function errorHandler(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert (‘You have denied access to your position.’);
break;
case error.POSITION_UNAVAILABLE:
alert (‘There was a problem getting your position.’);
break;
case error.TIMEOUT:
alert (‘The application has timed out attempting to
get your position.’);
break;
}
}
</script>   

 
</head>
<body>
<input type=”button” value=”Display Location”
onClick=”getLocation()”/>
</body>
</html>    
In the code, if the application fails to find the current location of the user, then the errorHandler() function is invoked. The function is passed as the second parameter in the getCurrentPosition() method and is used to handle the errors occurred in the application. It obtains the error object which is of type PositionError from the API and compares it with the error codes specified in the switch-case statement. Depending on the error that has occurred, the appropriate case statement is executed and an alert message is displayed to the user.
Figure 19.5 shows the output displaying error message for geolocation application. The reason for displaying error is that the Chrome browser blocks the URL whose file path starts with file:///.


PositionOptions Object
PositionOptions object is an optional third parameter passed to the getCurrentPosition() method. This object defines properties that are optional and are used by an application while retrieving the geolocation information.


Attribute     Description       
enableHighAccuracy     Indicates that the application wants to receive the most accurate results for geolocation. The default value of the attribute is false   



 
Attribute     Description       
maximumAge     Obtains the cached position object whose age is less than the specified maximumAge limit (in milliseconds). If age limit is set to 0, then the application must obtain a new position object       
timeout     Indicates the maximum time length (in milliseconds) for which the application can wait to obtain the position object       
<script>
var options = {
enableHighAccuracy: true,
maximumAge: 50000,
timeout: 60000
};
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,
errorHandler, options);
}
else{
alert (“Geolocation is not supported in this browser.”);
}
}
. . .
</script>    



n the code, an object named options is set with attributes. The attribute maximumAge enables the application to use a cached position object which is not older than 50 seconds. Also, the timeout limit is set to 60 seconds for an application, before notifying an error.
The options is passed as third parameter to the getCurrentPosition() method.

Google Maps API
The Google Maps API is used to display locations on a map based on the values of their coordinates - latitude and longitude. The Google Maps API must be configured in JavaScript, before it can be referenced further on the page. It contains a Map object which is instantiated and displayed on a Web page.
The syntax shows the configuration of Google Maps API in JavaScript.
Syntax:
<script src=”http://maps.google.com/maps/api/js?sensor=false”>
</script>
where,
src: Is the URL of Google Maps API
sensor: Parameter sent with the URL. It indicates whether application uses any sensor, such as GPS system to obtain the location of a user. Its value must be explicitly set to true or false
Code Snippet 5 demonstrates how to load and initialize the Google Maps API in the <script> tag. The code will execute after the page is loaded completely and will invoke a function in response to the onload event.

<!DOCTYPE html>
<html>
<head>
<title> Load and Initialize Google Maps </title>
<style>
html { height: 100% }
body { height: 100%; width: 100%; margin: 10% }
#map_canvas { height: 50%; width: 50% }
</style>
<script src=”http://maps.google.com/maps/api/js?sensor=false”></ script>
<script>   


In the code, the URL “http://maps.google.com/maps/api/js?sensor=false” definesall symbols and definitions to be loaded for the Google Maps API. Then, the function initialize() is invoked after the page is loaded completely. This function creates the object of type Map and initializes it with the map initialization variables.
In the function, var myOptions = {}, is an object of type options that contains properties, such as zoom, center, and mapTypeId. These properties are used to initialize the map.
Then, the statement new google.maps.Map (document.getElementById (“map_canvas”), myOptions); creates an instance of Map object. The object is displayed in a container on the Web page specified with the <div> element.

Finally, to display an icon on the identified location on the Google maps, the Marker object is created. The Marker object’s constructor sets the value for the properties, such as position, map, and title. The position property is specified with the location of the marker on the map. The map property is specified with the Map object to attach the marker with the map. Also, the title property sets the title to be displayed as a tooltip on the map.
As mentioned earlier, the myOptions object has several properties.


Property     Description       
zoom     Sets the initial resolution at which map is displayed. A lower zoom value 0 represents a full map of the Earth. Similarly, a higher zoom value displays a map with high resolution. In Code Snippet 5, the zoom level is set to 16.       
center     Centers the map on a specific point by creating an object of type LatLng which holds the location coordinates. In Code Snippet 5, the map is centered with the location coordinates 51.528663,- 0.173171. These coordinates display a map centered on Lord’s Cricket Ground in London, England.       
mapTypeId     Sets an initial map type. The map types supported are: ROADMAP for normal, SATELLITE for photographic tiles, HYBRID for roads and city names, and TERRAIN for water features. In Code Snippet 5, the map type has been set as google.maps.MapTypeId.HYBRID.    

Tracking User’s Location on Google Maps
The Geolocation object is used by the Google Maps API to display the geolocation information in the applications.
Code Snippet 6 demonstrates the code that displays current location of a user on the map using Geolocation object.
Code Snippet 6:

<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
html, body {
width: 100%;
height: 100%;
padding: 10%
}
#map_canvas {
height: 50%;
width: 50%;
}
</style>
<script src=”http://maps.google.com/maps/api/js?sensor=false”>
</script>
<script>
// Check support for Geolocation in the browser
if (navigator.geolocation) {
// Locate position and invoke function
navigator.geolocation.getCurrentPosition(displayPosition,
errorFunction);
} else {
alert(‘Geolocation is not enabled in your browser’);
}   
 
<body>
<div id=”map_canvas”></div>
<div id=”user_location”></div>
</body>
</html>    

The code uses the getCurrentPosition() method and retrieves the current position of the user. Then, it passes the information to displayPosition() function, which retrieves the coordinates, latitude and longitude. The retrieved coordinates are set into the properties of the Options object named myOptions and initialize the Map object. Finally, the Map object is displayed along with the current position information in the <div> element.
Drag Operation
HTML5 defines drag-and-drop operations that are based on events. The event-based mechanism allow the elements to be copied, reordered, or deleted on a Web page. The drag-and-drop operation involves the use of a pointing device, such as mouse on a visual medium. To perform the drag operation, a mousedown event is triggered followed by multiple mousemove events. Similarly, the drop operation is performed when a user releases the mouse.
The benefit of drag-and-drop mechanism is that it has brought the drag-and-drop operations on the browser level. This makes the programming easier, thus eliminating the need of complex JavaScript code written in earlier HTML versions.

<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop API</title>
</head>
<body>
<div id=”div” style=”border: red 2px solid; height:125px;
width:75px; padding: 10px”>
<img src=”image.jpg” height=”75” width=”75” id=”image1”
draggable=”true”/>
</div>
</body>
</html>    

Drag Events
During various stages of the drag-and-drop operation, a number of events are fired. These events are mouse-based events.

Events     Description       
dragstart     Triggers when an element is started to be dragged by the user       
drag     Triggers when an element is being dragged using a mouse       
dragleave     Triggers when the drag and drop operation is completed       
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Drag and Drop API</title>
<script>
function drag_image(event)
{
event.dataTransfer.setData(“image”, event.target.id);
}
</script>
</head>   


Drop Operation
After the element has been set up for dragging, it can be dropped on some element on the Web page. By default, elements on the page are not set up to receive dragged elements. Thus, the behavior of element acting as a drop element must be changed. This can be done by creating event listeners for the drop element. The drop element is also referred to as target element.
19.5.5 Drop Events
For any element to receive the drop operation, it must be associated with the drop events.

Event     Description       
dragenter     Triggers when a draggable element is being dragged on the target element for the first time       
dragleave     Triggers when an element is dragged outside the target element       
dragover     Triggers when an element is dragged inside the target element       
drop     Triggers when an element is dropped in the target element    
 
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Drag and Drop API</title>
<script>
function drag_image(event)
{
event.dataTransfer.setData(“image”, event.target.id);
}
function allow_drop(event)
{
event.preventDefault();
}
function drop_image(event)
{
var data=event.dataTransfer.getData(“image”);
event.target.appendChild(document.getElementById(data));



}
</script>
</head>
<body>
<div id=”div1” style=”border: blue 2px solid; height:125px;
width:75px; padding: 10px”>
<img src=”image.jpg” height=”75” width=”75” id=”image1”
draggable=”true” ondragstart=”drag_image(event)”/>
</div>
<br/>
<div id=”div2” style=”border: red 2px solid; height:125px;
width:75px; padding: 10px” ondrop=”drop_image(event)”
ondragover=”allow_drop(event)”>
</div>
</body>
</html>    
   


Offline Web Applications API
Consider a situation where a user is travelling outside the coverage area of Internet Service Provider (ISP). In this case, the user will not be able to access Web applications due to the network connection failure.
HTML5 supports offline Web applications that allow a user to work with them without being online. Offline Web applications work by saving all the Web pages locally on the user’s system. This feature is known as the Application Cache.
The Application Cache enables all resources, such as HTML, JavaScript, images, and CSS pages of an Web application to be stored locally on the system.
The following are the steps that can be taken to cache resources locally on the system:
Create a manifest file to define the resources that need to be saved.
Reference the manifest file in each Web page designed to use cached resources.
1. 2. 50 of 590 Concepts Session 19 HTML5 Geolocation and APIs V 1.1 © Zetutorials.blogspot.com  Limited
19.6.1 Creating a Manifest File
The manifest file is a text file that defines the caching behavior for resources used by the Web page. The file should be saved with the .manifest extension.
Code Snippet 10 demonstrates how to create a manifest file.
Code Snippet 10:

CACHE:
# Defines resources to be cached.
check.js
styles.css
images/figure1.jpg
FALLBACK:
# Defines resources to be used if non-cached resources cannot be #downloaded
Other_images/ figure2.png
NETWORK:
# Defines resources that will not be cached.    

HTML5 Geolocation and APIs
You will view and practice how to use new API in HTML5.
Working with Geolocation
and Google Maps APIs
             Working with the Drag and Drop API


                                                                                                                             Thank u
                                                                                                                 For watching  my website
                                                                                                                  Zetutorials.blogspot.com

No comments:

Post a Comment