HTML5 Geolocation and APIs-1
HTML5 Geolocation and APIs-1
nl
O
se
U
tre
en
Session: 19
C
h
ec
APIs
Fo
Explain geolocation and its use in HTML5
Explain
y
Explain
nl
the Google Maps API
O
the drag-and-drop operations in HTML5
se
U
tre
en
C
h
ec
pt
rA
Fo
O
se
The location of the user is represented as a single point that comprises two
components: latitude and longitude.
U
tre
Following figure shows the representation of latitude and longitude with respect
to a location on the globe.
en
C
h
ec
pt
rA
Fo
y
The different sources through which devices can determine the information about
nl
the location are as follows:
O
Global Positioning System (GPS)
• GPS is a satellite navigation system that provides information about the location on
se
any part of the globe.
• The GPS system is maintained by the government of the United States.
U
IP Address
tre
• Location information can be derived from IP Address which is assigned to devices,
en
such as desktops, printers, and so on connected on a network.
C
• These are used by the cell phones.
h
ec
WiFi and Bluetooth MAC address
• These are used by devices that have wireless network connection.
pt
rA
User Input
• It is a software tool which can be used on any device requesting for location
information.
Fo
• The information retrieved by the tool is based on the data provided by the user. For
example, a zip code.
nl
consistent way to develop location-aware Web applications.
O
The Geolocation API provides a high-level interface to retrieve location
se
information related to the hosting devices.
U
The interface hides the details, such as how the information is gathered or which
tre
methods were used to retrieve the information.
en
The object that holds implementation of the Geolocation API is the Geolocation
object.
C
h
This object is used in JavaScript to retrieve the geographic information about the
ec
devices programmatically.
pt
The browser processes the script and returns the location to the Geolocation
rA
API.
Fo
y
Following table lists the browsers providing support for Geolocation API.
nl
O
Browser Version Support
se
Safari 5.0+
U
Chrome 5.0+
tre
Firefox 3.5+
en
Internet 9.0+
C
Explorer h
Opera 10.6+
ec
Safari)
rA
Android 2.0+
Fo
Blackberry 6+
O
object.
se
The navigator object is a browser object that allows a user to retrieve
information about the specific location.
U
tre
Following syntax shows how to create a Geolocation object in JavaScript.
en
Syntax:
C
var geolocation = window.navigator.geolocation;
h
ec
y
The Code Snippet demonstrates the script that tests the existence of
nl
geolocation object within a browser.
O
<!DOCTYPE html>
<html>
se
<head>
<title> Testing Support for Geolocation in Browsers</title>
U
<script>
function display_location_enabled()
tre
{
// Default message
en
var str = “Geolocation is not supported in this browser”;
if (window.navigator.geolocation)
{
C
str = “Geolocation is supported in this browser”;
h
ec
}
alert (str);
pt
}
</script>
rA
</head>
<body>
Fo
y
in the browser.
nl
If browser provides implementation for the property, then an alert window
O
displays the message Geolocation is supported in this
browser .
se
Otherwise, the default message is displayed.
U
Following figure shows the existence of geolocation object in the Chrome
browser.
tre
en
C
h
ec
pt
rA
Fo
y
The geolocation object provides three methods that can be used to determine
nl
the current position of the user.
O
Following table lists the methods of the geolocation object.
se
U
Method Description
tre
getCurrentPosition() Retrieves the current geographic location
en
information of the user
C
watchPosition() Retrieves the geographic information of the device
at regular intervals
h
ec
clearWatch() Terminates the current watch process
pt
rA
Fo
O
getCurrentPosition(successCallback, errorCallback, options).
se
U
This function accepts three parameters, out of which two are optional,
errorCallback and options.
tre
en
The first parameter, successCallback is the name of the function which is
C
invoked after the position of a device is found successfully.
h
ec
The second parameter, errorCallback is the name of the function which will
be called, if an error occurs in retrieving the position.
pt
rA
y
the user.
nl
<!DOCTYPE html>
O
<html >
<head>
se
<title>Geolocation API</title>
U
<script>
function getLocation()
tre
{
if (navigator.geolocation) {
en
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
C
alert (“Geolocation is not supported in this browser.”);
h
}
ec
}
function showPosition(position)
pt
{
rA
}
</script>
</head>
© Aptech Ltd. HTML5 Geolocation and APIs / Session 19 12
y
<body>
nl
<input type=”button” value=” Display Location”
O
onClick=”getLocation()”/>
</body>
se
</html>
U
In the code, the getCurrentPostion() function obtains the position which is
tre
passed as a parameter to the showPosition() function.
The showPosition() function obtains the coordinates of a location through
en
position object.
C
The position object is defined in the Geolocation API and holds the current
location of the device.
h
It contains attribute named coords that retrieves the latitude and longitude of
ec
the location.
The values retrieved for latitude and longitude are in decimal degrees.
pt
rA
Fo
y
Following table lists the attributes of the position object.
nl
O
Attribute Description
se
coords An object of type Coordinates that provides different properties,
such as latitude, longitude, altitude, accuracy, speed, and so on.
U
timestamp An object of type DOMTimeStamp.
tre
en
Following figure shows the notifications for the Web page containing
geolocation code.
C
h
ec
pt
The browser seeks permission from the user to share their location information
rA
y
Following figure shows a message displaying current location of the user, when
nl
the Share My Location button is clicked.
O
se
U
tre
en
C
h
ec
pt
rA
Fo
y
An application could fail in gathering geographic location information. In that
nl
case, the geolocation object calls an errorCallback() function.
O
The errorCallback() function handles errors by obtaining a
PostionError object from the API.
se
HTML
U
tre
The PositionError object holds information related to errors occurred while
finding the geographic location of the user.
en
Following table lists the properties of PositionError object.
Property C Description
h
ec
y
Following table lists the different error codes returned by the code property of
nl
the PositionError object.
O
Code Constant Description
se
1 PERMISSION_DENIED Application does not have permission to access
U
Geolocation API.
tre
2 POSITION_UNAVAILABLE
Position of the device could not be obtained.
en
3 TIMEOUT Unable to retrieve location information within the
C
specified interval.
h
The Code Snippet demonstrates the error handling routine for the geolocation code.
ec
<!DOCTYPE html>
pt
<html>
rA
<head>
Fo
<title>Handling Error</title>
y
function getLocation()
nl
{
O
function showPosition(position)
{
se
alert(‘Latitude: ‘ + position.coords.latitude + ‘\n’ +
‘Longitude: ‘ + position.coords.longitude);
U
}
tre
function errorHandler(error) {
switch (error.code) {
en
case error.PERMISSION_DENIED:
alert (‘You have denied access to your position.’);
break;
C
case error.POSITION_UNAVAILABLE:
h
alert (‘There was a problem getting your position.’);
ec
break;
case error.TIMEOUT:
pt
}
}
</script> </head>
© Aptech Ltd. HTML5 Geolocation and APIs / Session 19 18
<body>
y
<input type=”button” value=”Display Location”
nl
onClick=”getLocation()”/>
O
</body> </html>
se
In the code, if application fails to find the current location of the user, then the
errorHandler() function is invoked.
U
The function is passed as the second parameter in the getCurrentPostion()
method and is used to handle the errors occurred in the application.
tre
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.
en
Depending on the error occurred, the appropriate case statement is executed
C
and an alert message is displayed to the user.
Following figure shows the output displaying error message for geolocation
h
application.
ec
pt
rA
Fo
The reason for the error is that the Chrome browser blocks the URL whose file
path starts with file:///.
© Aptech Ltd. HTML5 Geolocation and APIs / Session 19 19
y
PositionOptions object is an optional third parameter passed to the
nl
getCurrentPosition() method.
O
This object defines properties that are optional and are used by an application
while retrieving the geolocation information.
se
Following table lists the attributes of PositionOptions object.
U
Attribute Description
tre
Indicates that the application wants to receive the most
en
enableHighAccuracy
accurate results for geolocation. The default value of the
attribute is false.
C
h
maximumAge Obtains the cached position object whose age is less than
ec
the specified maximumAge limit (in milliseconds). If age
limit is set to 0, then the application must obtain a new
pt
position object.
rA
y
The Code Snippet demonstrates the script to set the attributes of
nl
PositionOptions object.
O
<script>
var options = {
se
enableHighAccuracy: true,
U
maximumAge: 50000,
timeout: 60000
tre
};
function getLocation() {
en
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,
} C
errorHandler, options);
h
else{
ec
}
rA
. . .
</script>
Fo
y
nl
In the code, an object named options is set with attributes.
O
The attribute, maximumAge enables the application to use a cached position
se
object which is not older than 50 seconds.
U
Also, the timeout limit is set to 60 seconds for an application, before notifying
an error.
tre
en
The options is passed as third parameter to the getCurrentPosition()
method.
C
h
ec
pt
rA
Fo
nl
their coordinates, latitude and longitude.
O
se
The Google Maps API must be configured in JavaScript, before it can be
referenced further on the page.
U
tre
It contains a Map object which is instantiated and displayed on a Web page.
en
Following syntax shows the configuration of Google Maps API in JavaScript.
Syntax: C
h
ec
<script src=”http://maps.google.com/maps/api/js?sensor=false”>
</script>
pt
src:
rA
where,
sensor:
Is the URL of Google Maps API.
Fo
y
The Code Snippet demonstrates how to load and initialize the Google Maps API in
nl
the <script> tag.
O
The code will execute after the page is loaded completely and will invoke a function
in response to the onload event.
se
U
<!DOCTYPE html>
<html>
tre
<head>
<title> Load and Initialize Google Maps </title>
en
<style>
html { height: 100% }
C
body { height: 100%; width: 100%; margin: 10% }
h
#map_canvas { height: 50%; width: 50% }
ec
</style>
<script
pt
src=”http://maps.google.com/maps/api/js?sensor=false”>
</script>
rA
Fo
nl
{
// Loading Google Maps
O
var num = new google.maps.LatLng(51.528663,-0.173171);
se
var myOptions = {
zoom: 16,
U
center: num,
mapTypeId: google.maps.MapTypeId.HYBRID
tre
};
var mymap = new google.maps.Map(document.getElementById(“
en
map_canvas”), myOptions);
var marker = new google.maps.Marker({
C
position: num,
map: mymap,
h
title:”Lord’s Cricket Ground, London!”
ec
});
}
pt
</script>
rA
</head>
<body onload=”initialize()”>
Fo
<div id=”map_canvas”></div>
</body>
</html>
© Aptech Ltd. HTML5 Geolocation and APIs / Session 19 25
I the ode, the U‘L http://maps.google.com/maps/api/js ?
y
sensor=false defi es all symbols and definitions to be loaded for Google Maps
nl
API.
O
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
se
initialization variables.
U
In the function, var myOptions = {}, is an object of type options that
contains properties, such as zoom, center, and mapTypeId.
tre
These properties are used to initialize the map.
Then, the statement new google.maps.Map
en
(document.getElementById (“map_canvas”), myOptions);
creates an instance of Map object.
C
The object is displayed in a container on the Web page specified with the <div>
h
element.
ec
Finally, to display an icon on the identified location on the Google maps, the
Marker object is created.
pt
The Marker o je t s o stru tor sets the alue for the properties, su h as
rA
The position property is specified with the location of the marker on the map.
Fo
The map property is specified with the Map object to attach the marker with the
map.
The title property sets the title to be displayed as a tooltip on the map.
© Aptech Ltd. HTML5 Geolocation and APIs / Session 19 26
y
Following table lists some of the myOptions properties.
nl
O
se
Property Description
U
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
tre
value displays a map with high resolution.
en
center Centers the map on a specific point by creating an object of type
LatLng which holds the location coordinates.
mapTypeId C
Sets an initial map type. The map types supported are: ROADMAP for
h
normal, SATELLITE for photographic tiles, HYBRID for roads and city
ec
y
nl
Cricket Ground in London.
O
se
U
tre
en
C
h
ec
pt
rA
Fo
y
The Geolocation object is used by the Google Maps API to display the
nl
geolocation information in the applications.
The Code Snippet demonstrates the code that displays current location of a user on
O
the map using Geolocation object.
se
<!DOCTYPE
<script> html>
U
<html
//lang=”en”>
Check support for Geolocation in the browser
<head>
tre
if (navigator.geolocation) {
<style>
//html,
Locate position
body { and invoke function
en
navigator.geolocation.getCurrentPosition(displayPosition,
width: 100%;
height: 100%;
errorFunction);
} padding: 10%
C
h
}
else {
ec
#map_canvas {
alert(‘Geolocation is not enabled in your browser’);
height: 50%;
}
pt
width: 50%;
}
rA
</style>
<script src=”http://maps.google.com/maps/api/js?sensor=false”>
Fo
</script>
nl
function
var mapdisplayPosition(position) {
= new google.maps.Map(document.getElementById(“
var my_lat = position.coords.latitude;
map_canvas”), myOptions);
O
var my_lng = position.coords.longitude;
se
var div_info
// Displays icon=on
document.getElementById(‘user_location’);
the located position
div_info.innerHTML
var = ‘<h1> Latitude is :’ + my_lat + ‘ and
marker = new google.maps.Marker({
+ ‘</h1>’;
U
Longitudeposition:
is + my_lng
latlng,
tre
// Load Google
map:Maps
map,
var latlngtitle:”User location”
= new google.maps.LatLng(my_lat, my_lng);
en
var myOptions
}); = {
} zoom: 2, //the initial resolution is set at which map is
center:
// Error latlng,
callback C
//displayed
//centers the map
function
h
mapTypeId:
function google.maps.MapTypeId.ROADMAP
errorFunction(pos) { //sets the map type
ec
};alert(‘Error!’);
pt
}
</script> </head>
rA
<body>
<div id=”map_canvas”></div>
Fo
<div id=”user_location”></div>
</body> </html>
y
The code uses the getCurrentPosition() method and retrieves the current
nl
position of the user.
Then, it passes the information to displayPosition() function, which retrieves
O
the coordinates, latitude and longitude.
se
The retrieved coordinates are set into the properties of the Options object named
myOptions and initialize the Map object.
U
Finally, the Map object is displayed along with the current position information in
the <div> element.
tre
Following figure shows the output displaying the current location of the user on the
en
Google Maps.
C
h
ec
pt
rA
Fo
O
se
The event-based mechanism allow the elements to be copied, reordered, or
deleted on a Web page.
U
The drag-and-drop operation involves the use of a pointing device, such as
tre
mouse on a visual medium.
en
To perform the drag operation, a mousedown event is triggered followed by
C
multiple mousemove events. h
ec
Similarly, the drop operation is performed when a user releases the mouse.
pt
This makes the programming easier, thus eliminating the need of complex
JavaScript code written in earlier HTML versions.
y
nl
1. Set the draggable attribute of an element to be dragged.
O
se
2. Set an ondragstart event on the element which stores the data being dragged.
U
3. Store the data into the DataTransfer object.
tre
The Code Snippet shows how to set the draggable attribute of an image
en
element.
<!DOCTYPE html>
<html>
<head> C
h
<title>Drag and Drop API</title>
ec
</head>
<body>
pt
draggable=”true”/>
</div>
</body> </html>
© Aptech Ltd. HTML5 Geolocation and APIs / Session 19 33
y
During various stages of the drag-and-drop operation, a number of events are fired.
nl
These events are mouse-based events.
O
Following table lists the various events triggered during the drag operation.
se
U
Event Description
tre
dragstart Triggers when an element is started to be dragged by the user.
en
drag Triggers when an element is being dragged using a mouse.
dragleave C
Triggers when the drag and drop operation is completed.
h
ec
pt
rA
Fo
y
nl
data in the drag-and-drop operation.
It allows getting and setting of the data being dragged.
O
In other words, the dataTransfer object holds the data during drag-and-drop
se
operation.
The dataTransfer Object enables to define two types of information.
U
These are as follows:
tre
The data type of the draggable element
The value of the data being stored in the data store
en
The Code Snippet demonstrates how to associate an element with dragstart
event to store the data being dragged.
<!DOCTYPE
<body> html> C
h
<divlang=”en”>
<html id=”div1” style=”border: blue 2px solid; height:125px;
ec
<script>
draggable=”true” ondragstart=”drag_image(event)”/>
rA
</div>function drag_image(event)
</body> {
event.dataTransfer.setData(“image”, event.target.id);
Fo
</html>
}
</script> </head>
© Aptech Ltd. HTML5 Geolocation and APIs / Session 19 35
y
In the code, the <img> element has been set with an event listener for the
nl
dragstart event.
O
When the image is dragged, then the dragstart event is fired and calls
drag_image() function.
se
The function uses the dataTransfer object to store the data during drag-and-
drop operation.
U
The stri g image represe ts the data type a d event.target.id represents
tre
the value of id attribute of the draggable element.
Following figure shows the output of the image element to be dragged.
en
C
h
ec
pt
rA
Fo
se
U
By default, elements on the page are not set up to receive dragged elements.
tre
en
Thus, the behavior of element acting as a drop element must be changed
C
h
ec
This can be done by creating event listeners for the drop element.
pt
rA
y
For any element to receive the drop operation, it must be associated with the drop
nl
events.
O
Following table lists the events of the drop operation.
se
Event Description
U
Triggers when a draggable element is being dragged on the target
tre
dragenter
element for the first time.
en
dragleave Triggers when an element is dragged outside the target element.
dragover C
Triggers when an element is dragged inside the target element.
h
ec
y
The Code Snippet demonstrates how to set up event listeners to drop the image
nl
element on the target element.
O
<!DOCTYPE
<body> html>
<divlang=”en”>
<html id=”div1” style=”border: blue 2px solid; height:125px;
se
width:75px; padding: 10px”>
<head>
<title>Drag
<img and Dropheight=”75”
src=”image.jpg” API</title>width=”75” id=”image1”
U
<script>
draggable=”true” ondragstart=”drag_image(event)”/>
tre
function drag_image(event)
</div>
{
<br/>
<div event.target.id);
id=”div2” style=”border: red 2px solid; height:125px;
en
event.dataTransfer.setData(“image”,
} width:75px; padding: 10px” ondrop=”drop_image(event)”
function
{
</div> C
allow_drop(event)
ondragover=”allow_drop(event)”>
h
event.preventDefault();
</body>
ec
}
</html>
function drop_image(event)
pt
{
rA
var data=event.dataTransfer.getData(“image”);
event.target.appendChild(document.getElementById(data));
Fo
}
</script> </head>
y
In the code, the <div> ele e t ith id attri ute, set as div2 , is asso iated ith
nl
two event listeners namely, ondragover and ondrop.
O
se
The ondropover calls the allow_drop() function which prevents the default
behavior of the target element.
U
By default, the browsers do not support dropping of one elements on the other
tre
element.
en
To prevent the default behavior, the statement, event.preventDefault() is
invoked.
C
h
Then, the drop event is fired on the target element.
ec
Finally, it appends the dragged image as a element into the target element, div2.
Fo
y
Following figure shows the output of the drop operation, after the image is dragged
nl
on the target element.
O
se
U
tre
en
C
h
ec
pt
rA
Fo
y
HTML5 supports offline Web applications that allow a user to work with them
nl
without being online.
The offli e We appli atio s orks y sa i g all the We pages lo ally o the user s
O
system.
se
This concept is also known as Application Cache.
The Application Cache enables all resources, such as HTML, JavaScript, images, and
U
CSS pages of an Web application to be stored locally on the system.
tre
Following are the steps that can be taken to cache resources locally on the system.
en
1. Create a manifest file to define the resources that need to be saved.
C
h
2. Reference the manifest file in each Web page designed to use cached resources.
ec
pt
rA
Fo
y
nl
by the Web page.
The file should be saved with the .manifest extension.
O
The Code Snippet demonstrates creation of a manifest file.
se
CACHE:
U
# Defines resources to be cached.
check.js
tre
styles.css
images/figure1.jpg
en
FALLBACK:
C
# Defines resources to be used if non-cached resources cannot be
# downloaded
h
Other_images/ figure2.png
ec
NETWORK:
pt
figure3.png
Fo
y
Following are the sections defined in the .manifest file.
nl
O
CACHE
• This section defines resources, such as check.js, styles.css, and
se
figure1.png to be stored locally.
U
FALLBACK
tre
• This section defines alternative resource to be used, when the actual
en
resource is not available.
NETWORK
C
• This section specifies resources to be accessed when there is a network
h
connection. Resources in this section are not cached..
ec
pt
rA
Fo
y
To associate a manifest with a Web page, assign .manifest file to the attribute
nl
named manifest specified with the html element.
The Code Snippet demonstrates how to add the .manifest file in an HTML
O
document.
se
<!doctype html>
<html manifest=”appcache.manifest”>
U
<head>
tre
<title> Web Page </title>
<link rel=”stylesheet” href=”styles.css”/>
<script type=”text/javascript” src=”check.js”></script>
en
</head>
C
<body>
<input type=”button” value=”click Here...” onClick=”display()”/>
h
<img src=”images/figure1.jpg” width=”100” height=”100”/>
ec
</body>
</html>
pt
I the ode, the appcache.manifest is spe ified ith the <html> tag.
rA
The interpretation of the manifest file is similar to any other file reference.
The document uses a relative file path, as both the manifest file and HTML
Fo
document are located in the same directory.
By default, a Web page declaring manifest is cached automatically.
© Aptech Ltd. HTML5 Geolocation and APIs / Session 19 45
y
The benefit of Application Cache is that it improves the performance of a Web page
nl
by reducing the number of requests made to the Web server.
O
The Web server hosts the Web application to be accessed on the network.
Following figure shows how to enable the Work Offline mode in the Opera browser.
se
This enables to cache the resources of the Web application pages locally.
U
tre
en
C
h
ec
pt
rA
Fo
y
Following figure shows the cached Web page in the Opera browser.
nl
O
se
U
tre
en
C
h
ec
pt
rA
Fo
y
Geolocation determines the current location of a user on devices.
nl
O
The location is represented as a single point on a map that comprises two
se
components: latitude and longitude.
U
The Goelocation API is a specification provided by the W3C which provides a
consistent way to develop location-aware Web applications.
tre
Google Maps API is used to display the user s location on the map.
en
C
The object of type Map is created in JavaScript, before it can be referenced in
h
an HTML document.
ec
rA
HTML5 supports offline Web applications that allow a user to work with them
Fo