HTML5 Geolocation

TUTORIAL HOME
HTML5 Geolocation
❮ Previous Next ❯
The HTML Geolocation API is used to locate a user’s position.

Try It

Locate the User’s Position
The HTML Geolocation API is used to get the geographical position of a user.

Since this can compromise privacy, the position is not available unless the user approves it.

Note: Geolocation is most accurate for devices with GPS, like iPhone.

Browser Support
The numbers in the table specify the first browser version that fully supports Geolocation.

API
Geolocation 5.0 – 49.0 (http)
50.0 (https) 9.0 3.5 5.0 16.0
Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.

Using HTML Geolocation
The getCurrentPosition() method is used to return the user’s position.

The example below returns the latitude and longitude of the user’s position:

Example

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 +
    “
Longitude: ” + position.coords.longitude;
}

»
Example explained:

Check if Geolocation is supported
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 outputs 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;
    }
}
»
Displaying the Result in a Map
To display the result in a map, you need access to a map service, like Google Maps.

In the example below, the returned latitude and longitude is used to show the location in a Google Map (using a static image):

Example
function showPosition(position) {
    var latlon = position.coords.latitude + “,” + position.coords.longitude;

    var img_url = “https://maps.googleapis.com/maps/api/staticmap?center=
    “+latlon+”&zoom=14&size=400×300&sensor=false&key=YOUR_:KEY”;

    document.getElementById(“mapholder”).innerHTML = ““;
}
»
Google Map Script
How to show an interactive Google Map with a marker, zoom and drag options.

Location-specific Information
This page has demonstrated how to show a user’s position on a map.

Geolocation is also very useful for location-specific information, like:

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 on success. The latitude, longitude and accuracy properties are always returned. The other properties are returned if available:

Property Returns
coords.latitude The latitude as a decimal number (always returned)
coords.longitude The longitude as a decimal number (always returned)
coords.accuracy The accuracy of position (always returned)
coords.altitude The altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracy The altitude accuracy of position (returned if available)
coords.heading The heading as degrees clockwise from North (returned if available)
coords.speed The speed in meters per second (returned if available)
timestamp The date/time of the response (returned if available)
Geolocation Object – Other interesting Methods
The Geolocation object also has 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

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 +
    “
Longitude: ” + position.coords.longitude;
}

»

❮ Previous Next ❯

HTML YouTube Videos

Toggle navigation
TUTORIAL HOME
HTML YouTube Videos
❮ Previous Next ❯
The easiest way to play videos in HTML, is to use YouTube.

Struggling with Video Formats?
Earlier in this tutorial, you have seen that you might have to convert your videos to different formats to make them play in all browsers.

Converting videos to different formats can be difficult and time-consuming.

An easier solution is to let YouTube play the videos in your web page.

YouTube Video Id
YouTube will display an id (like XGSy3_Czz8k), when you save (or play) a video.

You can use this id, and refer to your video in the HTML code.

Playing a YouTube Video in HTML
To play your video on a web page, do the following:

Upload the video to YouTube
Take a note of the video id
Define an element in your web page
Let the src attribute point to the video URL
Use the width and height attributes to specify the dimension of the player
Add any other parameters to the URL (see below)
Example – Using iFrame (recommended)
<iframe width="420" height="315"
src=”https://www.youtube.com/embed/XGSy3_Czz8k“>

»
YouTube Autoplay
You can have your video start playing automatically when a user visits that page by adding a simple parameter to your YouTube URL.

Note: Take careful consideration when deciding to autoplay your videos. Automatically starting a video can annoy your visitor and end up causing more harm than good.

Value 0 (default): The video will not play automatically when the player loads.

Value 1: The video will play automatically when the player loads.

YouTube – Autoplay
<iframe width="420" height="315"
src=”https://www.youtube.com/embed/XGSy3_Czz8k?autoplay=1“>

»
YouTube Playlist
A comma separated list of videos to play (in addition to the original URL).

YouTube Loop
Value 0 (default): The video will play only once.

Value 1: The video will loop (forever).

YouTube – Loop
<iframe width="420" height="315"
src=”https://www.youtube.com/embed/XGSy3_Czz8k?playlist=XGSy3_Czz8k&loop=1“>

»
YouTube Controls
Value 0: Player controls does not display.

Value 1 (default): Player controls display.

YouTube – Controls
<iframe width="420" height="315"
src=”https://www.youtube.com/embed/XGSy3_Czz8k?controls=0“>

»
YouTube – Using or
Note: YouTube and were deprecated from January 2015. You should migrate your videos to use instead.

Example – Using (deprecated)
<object width="420" height="315"
data=”https://www.youtube.com/embed/XGSy3_Czz8k“>

»
Example – Using (deprecated)
src=”https://www.youtube.com/embed/XGSy3_Czz8k“>
»

❮ Previous Next ❯

HTML Plug-ins

Toggle navigation
TUTORIAL HOME
HTML Plug-ins
❮ Previous Next ❯
The purpose of a plug-in is to extend the functionality of a web browser.

HTML Helpers (Plug-ins)
Helper applications (plug-ins) are computer programs that extend the standard functionality of a web browser.

Examples of well-known plug-ins are Java applets.

Plug-ins can be added to web pages with the tag or the tag.

Plug-ins can be used for many purposes: display maps, scan for viruses, verify your bank id, etc.

To display video and audio: Use the

The Element
The element is supported by all browsers.

The element defines an embedded object within an HTML document.

It is used to embed plug-ins (like Java applets, PDF readers, Flash Players) in web pages.

Example

»
The element can also be used to include HTML in HTML:

Example

»
Or images if you like:

Example

»
The Element
The element is supported in all major browsers.

The element also defines an embedded object within an HTML document.

Web browsers have supported the element for a long time. However, it has not been a part of the HTML specification before HTML5.

Example
http://bookmark.swf
»
Note that the element does not have a closing tag. It can not contain alternative text.

The element can also be used to include HTML in HTML:

Example
http://snippet.html
»
Or images if you like:

Example
http://audi.jpeg
»

❮ Previous Next ❯

HTML5 Audio

TUTORIAL HOME
HTML5 Audio
❮ Previous Next ❯
Audio on the Web
Before HTML5, audio files could only be played in a browser with a plug-in (like flash).

The HTML5

Browser Support
The numbers in the table specify the first browser version that fully supports the

Element

Example

»
HTML Audio – How It Works
The controls attribute adds audio controls, like play, pause, and volume.

The element allows you to specify alternative audio files which the browser may choose from. The browser will use the first recognized format.

The text between the tags will only be displayed in browsers that do not support the

HTML Audio – Browser Support
In HTML5, there are 3 supported audio formats: MP3, Wav, and Ogg.

The browser support for the different formats is:

Browser MP3 Wav Ogg
Internet Explorer YES NO NO
Chrome YES YES YES
Firefox YES YES YES
Safari YES YES NO
Opera YES YES YES
HTML Audio – Media Types
File Format Media Type
MP3 audio/mpeg
Ogg audio/ogg
Wav audio/wav
HTML Audio – Methods, Properties, and Events
HTML5 defines DOM methods, properties, and events for the

This allows you to load, play, and pause audios, as well as set duration and volume.

There are also DOM events that can notify you when an audio begins to play, is paused, etc.

For a full DOM reference, go to our HTML5 Audio/Video DOM Reference.

HTML5 Audio Tags
Tag Description

❮ Previous Next ❯

HTML Comments

Toggle navigation
TUTORIAL HOME
HTML Comments
❮ Previous Next ❯
Comment tags are used to insert comments in the HTML source code.

HTML Comment Tags
You can add comments to your HTML source by using the following syntax:


Notice that there is an exclamation point (!) in the opening tag, but not in the closing tag.

Note: Comments are not displayed by the browser, but they can help document your HTML source code.

With comments you can place notifications and reminders in your HTML:

Example

This is a paragraph.


»
Comments are also great for debugging HTML, because you can comment out HTML lines of code, one at a time, to search for errors:

Example
<!– Do not display this at the moment
Mountain
–>
»
Conditional Comments
You might stumble upon conditional comments in HTML:

<!–[if IE 9]>
    …. some HTML here ….
<![endif]–>
Conditional comments defines some HTML tags to be executed by Internet Explorer only.

Test Yourself with Exercises!
Exercise 1 »   Exercise 2 »

❮ Previous Next ❯

HTML Elements

TUTORIAL HOME
HTML Elements
❮ Previous Next ❯
HTML Elements
An HTML element usually consists of a start tag and end tag, with the content inserted in between:

Content goes here…
The HTML element is everything from the start tag to the end tag:

My first paragraph.

Start tag Element content End tag

My First Heading

My first paragraph.

HTML elements with no content are called empty elements. Empty elements do not have an end tag, such as the
element (which indicates a line break).

Nested HTML Elements
HTML elements can be nested (elements can contain elements).

All HTML documents consist of nested HTML elements.

This example contains four HTML elements:

Example

My First Heading

My first paragraph.

»
Example Explained
The element defines the whole document.

It has a start tag and an end tag .

The element content is another HTML element (the element).

My First Heading

My first paragraph.

The element defines the document body.

It has a start tag and an end tag .

The element content is two other HTML elements (

and

).

My First Heading

My first paragraph.

The

element defines a heading.

It has a start tag

and an end tag

.

The element content is: My First Heading.

My First Heading

The

element defines a paragraph.

It has a start tag

and an end tag

.

The element content is: My first paragraph.

My first paragraph.

Do Not Forget the End Tag
Some HTML elements will display correctly, even if you forget the end tag:

Example

This is a paragraph

This is a paragraph

»
The example above works in all browsers, because the closing tag is considered optional.

Never rely on this. It might produce unexpected results and/or errors if you forget the end tag.

Empty HTML Elements
HTML elements with no content are called empty elements.

is an empty element without a closing tag (the
tag defines a line break).

Empty elements can be “closed” in the opening tag like this:
.

HTML5 does not require empty elements to be closed. But if you want stricter validation, or if you need to make your document readable by XML parsers, you must close all HTML elements properly.

Use Lowercase Tags
HTML tags are not case sensitive:

means the same as

.

The HTML5 standard does not require lowercase tags, but W3C recommends  lowercase in HTML, and demands  lowercase for stricter document types like XHTML.

At Omegas we always use lowercase tags.

❮ Previous Next ❯

HTML5 Video

Toggle navigation
TUTORIAL HOME
HTML5 Video
❮ Previous Next ❯
HTML Video Example. Courtesy of Big Buck Bunny.


»
Playing Videos in HTML
Before HTML5, a video could only be played in a browser with a plug-in (like flash).

The HTML5

Browser Support
The numbers in the table specify the first browser version that fully supports the

Element

Example

»
How it Works
The controls attribute adds video controls, like play, pause, and volume.

It is a good idea to always include width  and height attributes. If height and width are not set, the page might flicker while the video loads.

The element allows you to specify alternative video files which the browser may choose from. The browser will use the first recognized format.

The text between the tags will only be displayed in browsers that do not support the

HTML

Example

»
The autoplay attribute does not work in mobile devices like iPad and iPhone.

HTML Video – Browser Support
In HTML5, there are 3 supported video formats: MP4, WebM, and Ogg.

The browser support for the different formats is:

Browser MP4 WebM Ogg
Internet Explorer YES NO NO
Chrome YES YES YES
Firefox YES YES YES
Safari YES NO NO
Opera YES (from Opera 25) YES YES
HTML Video – Media Types
File Format Media Type
MP4 video/mp4
WebM video/webm
Ogg video/ogg
HTML Video – Methods, Properties, and Events
HTML5 defines DOM methods, properties, and events for the

This allows you to load, play, and pause videos, as well as setting duration and volume.

There are also DOM events that can notify you when a video begins to play, is paused, etc.

Example: Using JavaScript

Play/Pause Big Small Normal

Video courtesy of Big Buck Bunny.

»
For a full DOM reference, go to our HTML5 Audio/Video DOM Reference.

HTML5 Video Tags
Tag Description

❮ Previous Next ❯

HTML Multimedia

Toggle navigation
TUTORIAL HOME
HTML  Multimedia
❮ Previous Next ❯
Multimedia on the web is sound, music, videos, movies, and animations.

What is Multimedia?
Multimedia comes in many different formats. It can be almost anything you can hear or see.

Examples: Images, music, sound, videos, records, films, animations, and more.

Web pages often contain multimedia elements of different types and formats.

In this chapter you will learn about the different multimedia formats.

Browser Support
The first web browsers had support for text only, limited to a single font in a single color.

Later came browsers with support for colors and fonts, and images!

Audio, video, and animation have been handled differently by the major browsers. Different formats have been supported, and some formats require extra helper programs (plug-ins) to work.

Hopefully this will become history. HTML5 multimedia promises an easier future for multimedia.

Multimedia Formats
Multimedia elements (like audio or video) are stored in media files.

The most common way to discover the type of a file, is to look at the file extension.

Multimedia files have formats and different extensions like: .swf, .wav, .mp3, .mp4, .mpg, .wmv, and .avi.

Common Video Formats
MP4 is the new and upcoming format for internet video.

MP4 is recommended by YouTube.

MP4 is supported by Flash Players.

MP4 is supported by HTML5.

Format File Description
MPEG .mpg
.mpeg MPEG. Developed by the Moving Pictures Expert Group. The first popular video format on the web. Used to be supported by all browsers, but it is not supported in HTML5 (See MP4).
AVI .avi AVI (Audio Video Interleave). Developed by Microsoft. Commonly used in video cameras and TV hardware. Plays well on Windows computers, but not in web browsers.
WMV .wmv WMV (Windows Media Video). Developed by Microsoft. Commonly used in video cameras and TV hardware. Plays well on Windows computers, but not in web browsers.
QuickTime .mov QuickTime. Developed by Apple. Commonly used in video cameras and TV hardware. Plays well on Apple computers, but not in web browsers. (See MP4)
RealVideo .rm
.ram RealVideo. Developed by Real Media to allow video streaming with low bandwidths. It is still used for online video and Internet TV, but does not play in web browsers.
Flash .swf
.flv Flash. Developed by Macromedia. Often requires an extra component (plug-in) to play in web browsers.
Ogg .ogg Theora Ogg. Developed by the Xiph.Org Foundation. Supported by HTML5.
WebM .webm WebM. Developed by the web giants, Mozilla, Opera, Adobe, and Google. Supported by HTML5.
MPEG-4
or MP4 .mp4 MP4. Developed by the Moving Pictures Expert Group. Based on QuickTime. Commonly used in newer video cameras and TV hardware. Supported by all HTML5 browsers. Recommended by YouTube.
Only MP4, WebM, and Ogg video are supported by the HTML5 standard.

Audio Formats
MP3 is the newest format for compressed recorded music. The term MP3 has become synonymous with digital music.

If your website is about recorded music, MP3 is the choice.

Format File Description
MIDI .mid
.midi MIDI (Musical Instrument Digital Interface). Main format for all electronic music devices like synthesizers and PC sound cards. MIDI files do not contain sound, but digital notes that can be played by electronics. Plays well on all computers and music hardware, but not in web browsers.
RealAudio .rm
.ram RealAudio. Developed by Real Media to allow streaming of audio with low bandwidths. Does not play in web browsers.
WMA .wma WMA (Windows Media Audio). Developed by Microsoft. Commonly used in music players. Plays well on Windows computers, but not in web browsers.
AAC .aac AAC (Advanced Audio Coding). Developed by Apple as the default format for iTunes. Plays well on Apple computers, but not in web browsers.
WAV .wav WAV. Developed by IBM and Microsoft. Plays well on Windows, Macintosh, and Linux operating systems. Supported by HTML5.
Ogg .ogg Ogg. Developed by the Xiph.Org Foundation. Supported by HTML5.
MP3 .mp3 MP3 files are actually the sound part of MPEG files. MP3 is the most popular format for music players. Combines good compression (small files) with high quality. Supported by all browsers.
MP4 .mp4 MP4 is a video format, but can also be used for audio. MP4 video is the upcoming video format on the internet. This leads to automatic support for MP4 audio by all browsers.
Only MP3, WAV, and Ogg audio are supported by the HTML5 standard.

❮ Previous Next ❯

HTML Google Maps

Toggle navigation
TUTORIAL HOME
HTML Google Maps
❮ Previous Next ❯
Google Maps allows you to display maps on your web page:

A Basic Web Page
To demonstrate how to add a Google Map to a web page, we will use a basic HTML page:

Example

My First Google Map

My map will go here

»
Set the Map Size
Set the size of the map:

Example
<div id="map" style="width:400px;height:400px”>
»
Create a Function to Set The Map Properties
This example defines a Google Map centered in London, England:

Example
function myMap() {
    var mapOptions = {
        center: new google.maps.LatLng(51.5, -0.12),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.HYBRID
    }
var map = new google.maps.Map(document.getElementById(“map”), mapOptions);
}
»
Example Explained
The mapOptions variable defines the properties for the map.

The center property specifies where to center the map (using latitude and longitude coordinates).

The zoom property specifies the zoom level for the map (try to experiment with the zoom level).

The mapTypeId property specifies the map type to display. The following map types are supported: ROADMAP, SATELLITE, HYBRID, and TERRAIN.

The line: var map=new google.maps.Map(document.getElementById(“map”), mapOptions); creates a new map inside the

element with id=”map”, using the parameters that are passed (mapOptions).

Add the Google Maps API
Finally, show the map on the page!

The functionality of the map is provided by a JavaScript library located at Google. Add a script to refer to the Google Maps API with a callback to the myMap function:

Example
<script src="https://maps.googleapis.com/maps/api/js?callback=myMap“>
»
Go to our Google Maps Tutorial to learn more about Google Maps.

❮ Previous Next ❯

HTML5 Canvas

TUTORIAL HOME
HTML5 Canvas
❮ Previous Next ❯
The HTML element is used to draw graphics on a web page.

The graphic to the left is created with . It shows four elements: a red rectangle, a gradient rectangle, a multicolor rectangle, and a multicolor text.

What is HTML Canvas?
The HTML element is used to draw graphics, on the fly, via JavaScript.

The element is only a container for graphics. You must use JavaScript to actually draw the graphics.

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

Browser Support
The numbers in the table specify the first browser version that fully supports the element.

Element
4.0 9.0 2.0 3.1 9.0
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content.

The markup looks like this:

Note: Always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas. To add a border, use the style attribute.

Here is an example of a basic, empty canvas:

Example

»
Draw a Line
Example
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
»
Draw a Circle
Example
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
»
Draw a Text
Example
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
ctx.font = “30px Arial”;
ctx.fillText(“Hello World”,10,50);
»
Stroke Text
Example
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
ctx.font = “30px Arial”;
ctx.strokeText(“Hello World”,10,50);
»
Draw Linear Gradient
Example
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);

// Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,”red”);
grd.addColorStop(1,”white”);

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
»
Draw Circular Gradient
Example
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);

// Create gradient
var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,”red”);
grd.addColorStop(1,”white”);

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
»
Draw Image
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
var img = document.getElementById(“scream”);
ctx.drawImage(img,10,10);
»
HTML Canvas Tutorial
To learn all about HTML , Visit our full HTML Canvas Tutorial.

❮ Previous Next ❯