An application programming interface (API) is a series of “hooks” built in to
an application that allows external access to the application’s data and
functionality.
× click to
close
A Word of Caution
There will be numerous examples in these lessons where you may be able to try
out the code and play with them either in the "Try-it Editor " or create an
actual HTML page in NotePad.
I can not stress enough that every effort was made during the production of
this material, to make sure that the information was as accurate and current as
possible.
As you should already know, that due to the nature of what you are dealing
with (HTML, CSS and JavaScript), any little misstep can become very frustrating.
The best advice I can give you, is to read the material over carefully (several
times if necessary), and thoroughly check your work for grammatical and/or
syntax errors.
As you progress through all of this material, you may come across some minor
errors that were inevitably missed. Do not let that stop or hinder you.
If anything, my hope is that as you progress through these lessons, you will
have become aware and skillful enough to find your way through and figure them
out.
HTML Geolocation is used to locate a user's
position.
Locate the User's Position
The HTML Geolocation API is used to get the geographical position of a
user.
Since this can compromise user privacy, the position is not available unless
the user approves it.
Browser Support
The numbers in the table specify the first browser version that fully
supports Geolocation.
API
Geolocation
5.0
9.0
3.5
5.0
16.0
Note: Geolocation is much more accurate for devices with GPS, like
iPhone.
Using HTML Geolocation
Use the getCurrentPosition() method to get the user's position.
The example below is a simple Geolocation example returning the latitude and
longitude of the user's position:
Example
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not
supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
If supported, run the getCurrentPosition() method. If not, display a
message to the user
If the getCurrentPosition() method is successful, it returns a coordinates
object to the function specified in the parameter ( showPosition )
the showPosition() function gets the displays the Latitude and
Longitude
The example above is a very basic Geolocation script, with no error
handling.
Handling Errors and Rejections
The second parameter of the getCurrentPosition() method is used to handle
errors. It specifies a function to run if it fails to get the user's
location:
Example
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED: x.innerHTML =
"User denied the request for
Geolocation."
break; case error.POSITION_UNAVAILABLE: x.innerHTML =
"Location information is
unavailable."
break; case error.TIMEOUT: x.innerHTML =
"the request to get user location timed out."
break; case error.UNKNOWN_ERROR: x.innerHTML =
"An unknown error occurred."
break;
}
}
In the example above we use the returned latitude and longitude data to show
the location in a Google map (using a static image).
Another example for Geolocation would be a Google Map script that would show
an interactive map with a marker, zoom and drag options.
Location-specific Information
this page demonstrated how to show a user's position on a map. However,
Geolocation is also very useful for location-specific information.
Examples:
Up-to-date local information
Showing Points-of-interest near the user
Turn-by-turn navigation (GPS)
the getCurrentPosition() Method - Return Data
The getCurrentPosition() method returns an object if it is successful. the
latitude, longitude and accuracy properties are always returned. the other
properties below are returned if available.
Property
Description
coords.latitude
the latitude as a decimal number
coords.longitude
the longitude as a decimal number
coords.accuracy
the accuracy of position
coords.altitude
the altitude in meters above the mean sea level
coords.altitudeAccuracy
the altitude accuracy of position
coords.heading
the heading as degrees clockwise from North
coords.speed
the speed in meters per second
timestamp
the date/time of the response
Geolocation object - Other interesting Methods
watchPosition() - Returns the current position of the user and continues to
return updated position as the user moves (like the GPS in a car).
clearWatch() - Stops the watchPosition() method.
The example below shows the watchPosition() method. You need an accurate GPS
device to test this (like
iPhone):
Example
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition
(showPosition);
} else {
x.innerHTML = "Geolocation is not
supported by this browser."; }
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
It might seem complicated, but lets go through all the different parts of a
drag and drop event.
Make an Element Draggable
First of all: To make an element draggable, set the draggable attribute to
true:
<img draggable="true">
What to Drag - ondragstart and setdata()
...then, specify what should happen when the element is dragged.
In the example above, the ondragstart attribute calls a function,
drag(event), that specifies what data to be dragged. the datatransfer.setdata()
method sets the data type and the value of the dragged data:
function drag(ev) {
ev.datatransfer.setdata("text", ev.target.id);
}
In this case, the data type is "text" and the value is the id of the
draggable element ("drag1").
Where to Drop - ondragover
The ondragover event specifies where the dragged data can be dropped.
By default, data/elements cannot be dropped in other elements. To allow a
drop, we must prevent the default handling of the element.
this is done by calling the event.preventdefault() method for the ondragover
event:
event.preventdefault()
Do the Drop - ondrop
When the dragged data is dropped, a drop event occurs.
In the example above, the ondrop attribute calls a function, drop(event):
function drop(ev) {
ev.preventdefault();
var data = ev.datatransfer.getdata("text");
ev.target.appendChild(document.getElementById(data));
}
Code explained:
Call preventdefault() to prevent the browser default handling of the data
(default is open as link on drop)
Get the dragged data with the datatransfer.getdata() method. this method
will return any data that was set to the same type in the setdata()
method
the dragged data is the id of the dragged element ("drag1")
With local storage, web applications can store data locally within the user's
browser.
Before HTML5, application data had to be stored in cookies, included in every
server request. Local storage is more secure, and large amounts of data can be
stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and
information is never transferred to the server.
Local storage is per origin (per domain and protocol). All pages, from one
origin, can store and access the same data.
Browser Support
The numbers in the table specify the first browser version that fully
supports Local Storage.
API
Web Storage
4.0
8.0
3.5
4.0
11.5
HTML Local Storage Objects
HTML local storage provides two objects for storing data on the client:
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session (data is lost when the
browser tab is closed)
Before using local storage, check browser support for localStorage and
sessionStorage:
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
The localStorage Object
The localStorage object stores the data with no expiration date. the data
will not be deleted when the browser is closed, and will be available the next
day, week, or year.
Example
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem
("lastname");
Create a localStorage name/value pair with name="lastname" and value=
"Smith"
Retrieve the value of "lastname" and insert it into the element with id=
"result"
The example above could also be written like this:
// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;
The syntax for removing the "lastname" localStorage item is as follows:
localStorage.removeItem("lastname");
Note: Name/value pairs are always stored as strings.
Remember to convert them to another format when needed!
The following example counts the number of times a user has clicked a button.
In this code the value string is converted to a number to be able to increase
the counter:
Example
if (localStorage.clickcount) {
localStorage.clickcount =
Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the
button" +
localStorage.clickcount + " time(s).";
The sessionStorage object is equal to the localStorage object,
except that it stores the data for only one session. the data
is deleted when the user closes the specific browser tab.
The following example counts the number of times a user has clicked a button,
in the current session:
Example
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount)
+ 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the
button " +
sessionStorage.clickcount + " time(s) in this session.";