Realtime Location Tracking – Google Maps: HTML5

In this video tutorial, we show you how we can keep track of the visitor and locate him/her on Google Maps using geolocation API of HTML5.

This video tutorial is a continuation of previous videos, so please make sure to watch them before this:
HTML5 – Getting Started Guide
Geolocation API – Success Handler: HTML5
Geolocation API – Error Handle: HTML5
Google Maps Integration: HTML5
Adding Pin/Marker To Google Map: HTML5
Add Popup message To Google Map Pin: HTML5

JavaScript file
mySript.js

if( navigator.geolocation )
    {
        var optn = {
enableHighAccuracy: true,
            timeout: Infinity,
            maximumAge: 0   
        };
         var watchID = navigator.geolocation.watchPosition(success, fail, optn);    
    }
    
    else
     $("p").html("HTML5 Not Supported");

$("button").click(function(){
    
    if(watchID)
     navigator.geolocation.clearWatch(watchID);
     
    watchID = null;
    return false;
});

Here we are setting the 3rd parameter of watchPosition() method.
We’re enabling HighAccuracy, setting timeout to Infinity – i.e., it’ll keep looking for the location information for ever or until it gets it. We can set this to some numerical value and it’ll check till then before it’ll show a “Timed out” message to the user. maximumAge is set to 0, so that it fetches new location each time it’s asked for. If we set it to Infinity, it’ll forever show the cached data and will never fetch or update the new location information.

watchPosition() is a geolocation method, which keeps watching/fetching new user location data. This would be helpful for tracking users location information in realtime.

HTML file
index.html

<!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="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="js/myScript.js"></script>
</head>
<body>
<p id="map"></p>
<button>Stop</button>
</body>
</html>

We also have a stop button added to our index.html page, once the user clicks on that button, we call clearWatch() method of geolocation API and ask watchPosition() method to stop tracking the users location.

Video Tutorial: Realtime Location Tracking – Google Maps: HTML5


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

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



By combining all the things you have learnt in this Google MAPs and geolocation API video tutorial series, you can build real time location tracking applications, which returns users location on a map, pin points it. Combining this, you could store users initial and final location, store it in database, pin point both locations on Google MAP and show them the distance or route etc.

Source Code: Full JavaScript file

mySript.js

var watchID = null;
$(document).ready(function(){
    var optn = {
enableHighAccuracy: true,
            timeout: Infinity,
            maximumAge: 0   
        };
    if( navigator.geolocation )
     navigator.geolocation.watchPosition(success, fail, optn);
    else
     $("p").html("HTML5 Not Supported");
$("button").click(function(){
    
    if(watchID)
     navigator.geolocation.clearWatch(watchID);
     
    watchID = null;
    return false;
});
    
});

function success(position)
{
    var googleLatLng = new google.maps.LatLng(position.coords.latitude, 
                        position.coords.longitude);
    var mapOtn={
zoom:10,
center:googleLatLng,
mapTypeId:google.maps.MapTypeId.ROAD
    };
    
    var Pmap=document.getElementById("map");
    
    var map=new google.maps.Map(Pmap, mapOtn);
    addMarker(map, googleLatLng, "Technotip.com", 
                  "SATISH B
About Me:https://technotip.com/about/");
}

function addMarker(map, googleLatLng, title, content){
    var markerOptn={
position:googleLatLng,
map:map,
title:title,
animation:google.maps.Animation.DROP
    };
    
    var marker=new google.maps.Marker(markerOptn);
    
    var infoWindow=new google.maps.InfoWindow({ content: content, 
                                                   position: googleLatLng});
    google.maps.event.addListener(marker, "click", function(){
        infoWindow.open(map);
    });                                                
}

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);
}

You can integrate MAPs feature into your existing application and release this module to your users and impress them by telling their location or you can show other users nearby to their location, this would amaze some, as to how you could know about the person living nearby :-)

Remember the position.coords.accuracy property, which returns the accuracy value in meters?
Using this value, show all the users present around a users location with that accuracy(position.coords.accuracy).

Happy learning!

Add Popup message To Google Map Pin: HTML5

In this video tutorial we shall teach you how to add a message window(popup) when the pin or the marker is clicked on a Google Map.

pin-marker-google-map-message-infoWindow

JavaScript file
mySript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function addMarker(map, googleLatLng, title, content){
var markerOptn={
position:googleLatLng,
map:map,
title:title,
animation:google.maps.Animation.DROP
};
 
var marker=new google.maps.Marker(markerOptn);
 
var infoWindow=new google.maps.InfoWindow({ content: content, 
                                               position: googleLatLng});
    google.maps.event.addListener(marker, "click", function(){
infoWindow.open(map);
});   
}

Add the content and position information to InfoWindow constructor of Google Maps API.
Also add a event listener: once the marker is clicked, open the message window on the map.

Full JavaScript file
mySript.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
$(document).ready(function(){
 
if( navigator.geolocation )
 navigator.geolocation.getCurrentPosition(success, fail);
else
 $("p").html("HTML5 Not Supported");
 
});
 
function success(position)
{
var googleLatLng = new google.maps.LatLng(position.coords.latitude, 
position.coords.longitude);
var mapOtn={
zoom:10,
center:googleLatLng,
mapTypeId:google.maps.MapTypeId.ROAD
};
 
var Pmap=document.getElementById("map");
 
var map=new google.maps.Map(Pmap, mapOtn);
addMarker(map, googleLatLng, "Technotip.com", 
                  "SATISH B<br /><b>About Me:</b>https://technotip.com/about/");
}
 
function addMarker(map, googleLatLng, title, content){
var markerOptn={
position:googleLatLng,
map:map,
title:title,
animation:google.maps.Animation.DROP
};
 
var marker=new google.maps.Marker(markerOptn);
 
var infoWindow=new google.maps.InfoWindow({ content: content, 
                                               position: googleLatLng});
    google.maps.event.addListener(marker, "click", function(){
infoWindow.open(map);
});   
}
 
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);
}

For explanation of above code, please visit previous day videos.

Add Popup message To Google Map Pin/Marker Click Event: HTML5


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

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



Your location may not be shown accurately if you’re accessing the pages via your computer. Open above link in your smart phone, with GPS turned on.

Coming Up: Tracking real time location on Google Map..stay subscribed

Adding Pin/Marker To Google Map: HTML5

In this video tutorial we’ll show you how we can add a pin or marker to Google Map at a particular location.

location-pin-marker-map

This is a continuation video, so please watch below tutorials before proceeding:
HTML5 – Getting Started Guide
Geolocation API – Success Handler: HTML5
Geolocation API – Error Handle: HTML5
Google Maps Integration: HTML5

If you’re using a smart phone or any other GPS device, you can get to your exact location more accurately. To pin point your exact location, we can add a pin or the marker to your location.

Javascript File
myScript.js

1
2
3
4
5
6
7
8
9
10
function addMarker(map, googleLatLng, title){
var markerOptn={
position  : googleLatLng,
map:map,
title:title,
animation :   google.maps.Animation.DROP
};
 
var marker = new google.maps.Marker(markerOptn);
}

We do not generate map again. Since we already have it generated in success method, we’ll simply use the same map. We’ll get the position information from HTML5’s Geolocation API, convert it into googleLatLng object and pass to addMarker method. We also set some options for the marker, like the position, title and the animation. We could have two type of simple animation using properties BOUNCE and DROP. Finally pass the marker option to Marker constructor of google maps api. This would bring up the map with a nice little marker.

Full Javascript File: Google Map API
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
$(document).ready(function(){
 
if( navigator.geolocation )
 navigator.geolocation.getCurrentPosition(success, fail);
else
 $("p").html("HTML5 Not Supported");
 
});
 
function success(position)
{
var googleLatLng = new google.maps.LatLng(position.coords.latitude, 
 position.coords.longitude);
var mapOtn = {
zoom:10,
center   : googleLatLng,
mapTypeId: google.maps.MapTypeId.ROAD
}
 
var Pmap = document.getElementById("map");
 
var map = new google.maps.Map(Pmap, mapOtn);
addMarker(map, googleLatLng, "Technotip.com");
}
 
function addMarker(map, googleLatLng, title){
var markerOptn={
position: googleLatLng,
map:map,
title:title,
animation:google.maps.Animation.DROP
};
 
var marker = new google.maps.Marker(markerOptn);
}
 
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);
}

Please look at previous day videos to understand above code fully.

Adding Pin/Marker To Google Map: HTML5


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

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



We could even include our own marker image, by setting the icon to your image path in the marker options.
Example:

1
2
3
4
5
6
var markerOptn={
position  : googleLatLng,
map:map,
title:title,
icon:'myPin.png'
};

Google Maps Integration: HTML5

In this video tutorial we illustrate the implementation of Google Maps API.

Here we supply latitude and longitude values fetched by Geolocation API and feed it to Google Map API, which is turn returns the location on its MAP.

globe-latitude-longitude

It has 4 variations:
ROADMAP (normal, default 2D map)
SATELLITE (photographic map)
HYBRID (photographic map + roads and city names)
TERRAIN (map with mountains, rivers, etc.)

HTML File
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< !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="http://maps.google.com/maps/api/js?sensor=true"></script>
  <script src="js/myScript.js"></script>
 </head>
 <body>
  <p id="map"></p>
 </body>
</html>

Here we’ve added an id to paragraph tag. And included Google Map API’s javascript file within the head tag. We must include it before myScript.js, as we’ll be using Google Map API’s inside myScript.js

Javascript File: Google Map API
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function success(position)
{
var googleLatLng = new google.maps.LatLng(position.coords.latitude, 
  position.coords.longitude);
var mapOtn={
zoom:10,
center   : googleLatLng,
mapTypeId: google.maps.MapTypeId.ROAD
}
 
var Pmap= document.getElementById("map");
 
var map= new google.maps.Map(Pmap, mapOtn);
}

Pass position.coords.latitude and position.coords.longitude values to LatLng constructor of Google Maps API, which converts it into googleLatLng object.

Set the options of Google Maps:
zoom takes value from 0 to 21.
We center the map to our users/visitors location.
map type: ROADMAP, SATELLITE, HYBRID, TERRAIN.

Full Javascript File: Google Map API
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
34
35
36
37
38
39
40
41
$(document).ready(function(){
 
if( navigator.geolocation )
 navigator.geolocation.getCurrentPosition(success, fail);
else
 $("p").html("HTML5 Not Supported");
 
});
 
function success(position)
{
var googleLatLng = new google.maps.LatLng(position.coords.latitude, 
  position.coords.longitude);
var mapOtn= {
zoom:10,
center   :googleLatLng,
mapTypeId:google.maps.MapTypeId.ROAD
}
 
var Pmap= document.getElementById("map");
 
var map= new google.maps.Map(Pmap, mapOtn);
}
 
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);
}

For explanation of other parts of above code:
Geolocation API – Success Handler: HTML5
Geolocation API – Error Handle: HTML5

Google Maps API Integration: HTML5


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

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



Note:
If you’re accessing this application via your desktop computer, then it may be showing you the location of your ISP’s(Internet Service Provider’s) local office location.
To get the accurate location, access our demo page via your smart phone.

Google Maps: Demo

Smartphone
1. Install Google Chrome browser.
2. Switch on your GPS and permit Google to access your location information, for testing purpose.
3. Visit our demo link(present above).
4. Move around and see your location information being updated in real-time.
5. We’ll teach you to make your application show real time data in coming videos, stay subscribed :-)