Geolocation API – Error Handle: HTML5

This video tutorial teaches about error handle of Geolocation API – of HTML5.

It is a continuation of Geolocation API – Success Handler: HTML5

Cumputer-Bug-Error

This code is helpful when geolocation API is unable to determine the users location. In this situation we, as good developers, shouldn’t leave the user keep thinking about what happened! We should gracefully inform the user about what happened in the background of our application data center.

Javascript File
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function fail(error)
{
var errorType = {
0:"Unknown Error",
1:"Permission denied by the user",
2:"Position of the user not available",
3:"Request timed out"
};
 
var errMsg = errorType[error.code];
 
if(error.code == 0 || error.code == 2){
errMsg = errMsg+" - "+error.message;
}
 
$("p").html(errMsg);
}

Geolocation API passes error object to the error handle(fail method), which contains error.code and corresponding error.message properties, using which we output the error information to the user.

Error code starts from 0 through 3, which we customize by giving our own, user understandable error messages, inside an object called errorType.

If the error code is 0 or 2, we’ll also output the original error message(sent by geolocation API) associated with the error code along with our own custom error message.

Full Free Code
Javascript File
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$(document).ready(function(){
 
if( navigator.geolocation )
 navigator.geolocation.getCurrentPosition(success, fail);
else
 $("p").html("HTML5 Not Supported");
 
});
 
function fail(error)
{
var errorType = {
0: "Unknown Error",
1: "Permission denied by the user",
2: "Position of the user not available",
3: "Request timed out"
};
 
var errMsg = errorType[error.code];
 
if(error.code == 0 || error.code == 2){
errMsg = errMsg+" - "+error.message;
}
 
$("p").html(errMsg);
}
 
function success(position)
{
$("p").html("Latitude: "+position.coords.latitude+
            "<br />Longitude: "+position.coords.longitude+
"<br />Accuracy: "+position.coords.accuracy);
}

HTML5 page(index.html) and the CSS3(myStyle.css) are same as present in our previous video tutorial.

Geolocation API – Error Handle: HTML5


[youtube https://www.youtube.com/watch?v=j_5EGTb9dhA]

YouTube Link: https://www.youtube.com/watch?v=j_5EGTb9dhA [Watch the Video In Full Screen.]



We can control “request timeout” property of our application via options(3rd parameter) parameter of getCurrentPosition() method, which we’ll look in coming videos.

Next, we’ll integrate the output of geolocation API with Google Maps API and locate the actual position of the user on a MAP!

Geolocation API – Success Handler: HTML5

In this video tutorial we’ll show you how to write your first(simple) HTML5 geolocation API application. Basics of Geolocation API is also explained in the notes below, so don’t skip, read and practice it.

Technologies included
Basic HTML5 tags
jQuery – for Javascript
CSS basics

With Geolocation API we can know our position/location on earth by fetching the latitude and longitude information from the browser.

HTML5 File
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
< !doctype html>
<html>
 <head>
  <title>Geolocation API: Technotip.com</title>
  <meta charset="utf-8"/>
  <link href="css/myStyle.css" rel="stylesheet"/>
  <script src="js/jquery-1.10.1.min.js"></script>
  <script src="js/myScript.js"></script>
 </head>
 <body>
  <p></p>
 </body>
</html>

Here we’re making use of HTML5 markup.
Know more: HTML5 – Getting Started Guide

We’re also including a jQuery library file. Make sure to include it before our custom javascript file(myScript.js), as our javascript file depends on jQuery library file.

CSS File
myStyle.css

1
2
3
4
p{
width: 300px;
height: 300px;
}

This is a simple Cascading Stylesheet file, which is allocating 300px width and height to the paragraph tag present in index.html file. It’ll be helpful when we integrate Google Maps into our application( in the future videos ).

Javascript File
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function(){
 
if( navigator.geolocation )
 navigator.geolocation.getCurrentPosition(success);
else
 $("p").html("HTML5 Not Supported");
 
});
 
function success(position)
{
$("p").html("Latitude: "+position.coords.latitude+
            "<br />Longitude: "+position.coords.longitude+
"<br />Accuracy: "+position.coords.accuracy);
}

This is a minimalistic approach to using geolocation API. We’ll improve it in future videos.

Once the document is loaded and ready, we check if the browser supports Geolocation API.
We do that by checking if navigator.geolocation object exists.
If it doesn’t exist, we display appropriate message to the user(“HTML5 Not Supported”).

If it does support navigator.geolocation, we’ll make use of it’s methods and get the user location.
navigator.geolocation has 3 methods:
getCurrentPosition
watchPosition
clearWatch

In this video tutorial we’ll be looking at the first method, i.e., getCurrentPosition()

navigator.geolocation.getCurrentPosition(success, error, option);

getCurrentPosition()
It takes 3 parameters:
success handler
error handler
and options.

success handler is mandatory.
error handler and options are optional.

getCurrentPosition method passes the users current location information to the success handler, in the form of position object.

position object: success handler method

position object has two properies: coords and timestamp

coords(coordinates) inturn has 7 properties:
3 are supported by most browsers:
latitude
longitude
accuracy

..other 4 are not widely supported:
altitude
altitudeAccuracy
heading
speed

In this tutorial we’re using latitude, longitude and accuracy properties, as it’s supported by most browsers.

Geolocation API – Success Handler: HTML5


[youtube https://www.youtube.com/watch?v=a3-ekroQoHo]

YouTube Link: https://www.youtube.com/watch?v=a3-ekroQoHo [Watch the Video In Full Screen.]



Note:
1. Geolocation API returns latitude and longitude values in decimal number system.
2. It determines users location by using various factors like: IP Address, GPS, Cell phone triangulation, WiFi etc.
3. We can’t know or specify which method it has to use to determine the users location.
4. If you’re getting 404 or googleapi not found, [object][object] etc error messages, then reload your webpage after you restart your system and/or your WiFi modem.
Make sure your WiFi modem is ON: because it’s one of the way Geolocation API will fetch your location from.

Missing things:
Error handling.
Options, to configure maps output. etc
Showing the location of the user on a MAP.
Showing real time movement of the user on a MAP.
All these will be covered in future videos. Stay Subscribed. Share this video with your friends.

HTTP Server(request/response) Counter Application: Node.js

This video tutorial is a rapid application development to illustrate HTTP Server(request/response) using Node.js

In this video, we use HTTP Server(request/response): Node.js code and work on it to develop a simple counter application.

Using this application, we can know how many visits have been made since the last server down time!

For explanation of all the keywords and working, please visit HTTP Server(request/response): Node.js

HTTP Server
count.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 var http = require('http');
 var visits = 0;
 
 http.createServer( function(request, response) {
 
console.log('New Connection');
visits++;
 
response.writeHead(200, { 'Content-Type':'text/plain' } );
response.write('Hello\n');
response.write('We have had '+visits+' visits');
response.end();
 
 }).listen(8080);
 
 console.log('Server Started..');

Here we take a variable called visits and initialize it to 0.
Once there is a new connection request, we increment it’s value by 1.
Since there is also request from favicon, practically, there’ll be 2 requests simultaneously: hence the counter increments by 2 for each new connection request.

using write method, we print the number of visits.

HTTP Server(request/response) Counter Application: Node.js


[youtube https://www.youtube.com/watch?v=yRaMJy5Mot0]

YouTube Link: https://www.youtube.com/watch?v=yRaMJy5Mot0 [Watch the Video In Full Screen.]



Output:
Hello
We have had 3 visits

Note:
Once you stop the server or whenever there is down time in the server, the counter is reinitialized once the server is restarted.

Make use of Database to store the counter value, if you need it inspite of server downtime or restarts.

HTTP Server(request/response): Node.js

This video tutorial illustrates working of simple HTTP Server, using Node.js
We’ll show the request, response of our HTTP server using simple Node.js program.

We’ll create a HTTP Server, with some response text in it.
Then, send request using web browser and see to that our HTTP server responds appropriately.

HTTP Server
hello.js(using chaining of methods)

1
2
3
4
5
6
7
8
9
10
11
var http = require('http');
 
http.createServer( function(request, response){
 
 response.writeHead(200, { 'Content-Type': 'text/plain' });
 response.write('Welcome to Node!');
 response.end();
 
}).listen(8080);
 
console.log('Server Started');

OR

hello.js(without using chaining of methods)

1
2
3
4
5
6
7
8
9
10
11
12
13
var http = require('http');
 
var server = http.createServer( function(request, response){
 
 response.writeHead(200, { 'Content-Type': 'text/plain' });
 response.write('Welcome to Node!');
 response.end();
 
});
 
server.listen(8080);
 
console.log('Server Started');

In the first line, we require http module of node.js
http module is built into node.js package, to help build node.js applications.

Using this http, we’ll call createServer method, which returns an object. Using this object we’ll call another method listen and pass port number 8080 to be(reserve to be used) used to invoke our HTTP server.

createServer method takes a anonymous function as parameter.

Anonymous function: Method with no name.

This anonymous method takes two parameters: request and response.

request and response: These are two objects passed by our http server when it receives new connection requests.

Using response object we’ll call writeHead method and pass 2 parameters.
First being the status code: 200 (which means, everything is ok or successfully connected)
Second parameter specifies that, the content type is plain text.

Inorder to demonstrate that our HTTP server is indeed responding/working, we’ll output a simple string “Welcome to Node” onto our web browser, as a response text.

Using the object returned by createServer method, we’ll invoke another method called listen and then reserve port number 8080 for our HTTP Server request.

Server Start
To indicate the server start, using simple console.log we’ll indicate its start.

node-http-server-start

Server Start
Command Prompt

1
node hello.js

Navigate to the folder where hello.js file is located. Now using node command execute hello.js file.

Once “Server Started” message is given, open any web browser and goto localhost:8080 to ping / request our HTTP server.

HTTP Server ( Request / Response ): Node.js


[youtube https://www.youtube.com/watch?v=9DFbfXcSIOw]

YouTube Link: https://www.youtube.com/watch?v=9DFbfXcSIOw [Watch the Video In Full Screen.]



Output:
Welcome to Node!

Note:
If you make changes to the response text(as in our example), you’ll need to restart the server in order for the changes to reflect at the client end.

Close the server connection using ctrl+ c and restart it using node command followed by file name.

Access Specifiers: PHP OOP

Controlling Access with public, private and protected access modifiers.
These access specifiers can be used on both variables/attributes and methods.

In this video tutorial, we’ll demonstrate it using attributes.

Access Specifiers:
1. public
2. private
3. protected

Class With Attributes

1
2
3
4
5
6
7
8
9
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
?>

var $a is similar to writing public $a

We shall extend class container to another class called contains.
Extending class is an inheritance property, and we shall discuss inheritance in another article. For now, know that, with extends keyword, all the properties and methods with public / protected access are inherited.

Extends

1
2
3
4
5
6
7
8
9
10
11
12
13
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 }
?>

Here, contents of class container is extended by class contains.

Object of class container

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 }
 
 $obj1 = new container();
         echo $obj1->a;
         echo $obj1->b;
?>

This outputs: 10 and 20 respectively.

Object of class contains

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 }
 
 $obj2 = new contains();
         echo $obj2->a;
         echo $obj2->b;
?>

This outputs: 10 and 20 respectively.
i.e., public attributes are inherited

Accessing private / protected attributes outside class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 }
 
 $obj1 = new container();
         echo $obj1->c;
         echo $obj1->d;
?>

It through’s error, since you cannot access, private and protected variables/attributes outside the class.

Now lets check if private and protected variables are actually inherited:

Inheriting private attribute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 function __construct()
{
echo $this->c;
}
 }
 
 $obj1 = new contains();
?>

This through’s error, because $c is not inherited to class contains and thus not present inside class contains. Which means, private variables and methods cannot be inherited.

Inheriting protected attribute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 function __construct()
{
echo $this->d;
}
 }
 
 $obj1 = new contains();
?>

Output’s 40.
This means, protected variables and methods are inherited.

Access Specifiers: PHP OOP


[youtube https://www.youtube.com/watch?v=2Ow_cgBEGmk]

YouTube Link: https://www.youtube.com/watch?v=2Ow_cgBEGmk [Watch the Video In Full Screen.]



Conclusion
public attributes and methods are inherited and can be accessed outside the class.
private attributes and methods cannot be inherited and cannot be accessed outside the class.
protected attributes and methods can be inherited but cannot be accessed outside the class.