Click here to Skip to main content
13,548,896 members
Click here to Skip to main content
Add your own
alternative version

Stats

21.8K views
5.2K downloads
35 bookmarked
Posted 16 Jan 2016
Licenced CPOL

Learn HTML 5 in 3 days – Day 2 – Part 2

Rate this:
Please Sign up or sign in to vote.
This is part 2 day 2 continuation of article Learn HTML5 in 3 days.

Introduction

You are here means you are enjoying the series. If you want to know basic & other features then I really request you should go and check previous part first. Lets begin.

Complete List

Day 2 - Part 2 Agenda

  • Lab 14 - Web Worker
  • Lab 15 - Web Worker and Ajax
  • Lab 16 and Lab 17 - HTML5 Media - Video
  • Lab 18 and Lab 19 HTML5 Media - Audio
  • Lab 20 and Lab 21 - Drag and Drop
  • Lab 22 - Geo Location
  • Lab 23 - Geo Location with google map

Web Worker

What is Web Worker?

Before I take any further step, let me ask you a simple question. Have u ever end up with following error in your web application.

If yes then solution for this problem is Web Worker. (Appearance of error display may be different in different browser).

Long running JavaScript will make UI unresponsive and many times we may end up with above error. Only solution for such problem will be client side multi-threading. Unfortunately it was not possible earlier but now with HTML5, by using Web Worker we can implement multi-threading in client side world.

Let’s do a small demo to understand Web Worker

 

Lab 22- Understanding web Worker - Simple

This will be a very simple lab. Here will accept a number “N” from end user and then display sum of first “N” numbers.

Note: We will start our demo without Web Worker, Understand the output and then migrate it to Web Worker.

 

Step 1 : Create new Asp.Net Project

Open Visual studio. Click File>>New Project.

From the dialog box select Web in left section “Asp.Net Web Application” in right section and click Ok.

Select Empty in the next dialog box and click ok.

 

Step 2: Create HTML file

Put following HTML in the bodyWebWorker.Html file.

<input type="text" name="myText" id="myText" value=" " />
<input type="button" name="name" value="Generate" />

 

Step 3: Download Loading image

Get a GIF image of your choice from somewhere and name it loading.gif and place it in the project. (If you want you can download it from sample attached.)

 

Step 4: Download jQuery

Download jQuery file from jQuery.com or download it from sample attached and include it in the project.

Just on a quick note, jQuery is a JavaScript library which will make DOM manipulation and DOM traversing easier. In simple words, using this library we can easily program against HTML.

This lab or series won’t expect participant to have knowledge on jQuery. We will be using only some of the feature of jQuery here which will be explained.

 

Step 5: Include jQuery

Simply include jQuery script file in the head section of WebWorker.html file as follows.

<script src="jquery-1.4.4.min.js"></script>

 

Step 6 : Write long running Script

Create JavaScript 'Generate' function as follows.

<script type="text/javascript">
function Generate()
{
     $('#divData').html("Generating");
     $('.MyLoading').show();
     var j = 0;

     for (i = 0; i<= parseInt($('#myText').val()); i++)
     {
        j = j+ i;
     }
     $('#divData').html("Result is " + j);
     $('.MyLoading').hide();
}
</script>

In 'Generate' function following things are done one after the other.

  1. Display “Generating..” text
  2. Display Loading Image
  3. Perform logical operation(long running operation – Add first N numbers)
  4. Display the result
  5. Hide loading image.

Note: In above code,

  • $('#divData') - will return element with id “divData”
  • html - function sets inner HTML of an element
  • show and hide – will show or hide the element.

 

Step 7: Press F5 and test the application.

(In your case you may have to put some big number to get error.)

You can notice two things in response.

  • Putting big number in textbox makes the page unresponsive.
    Reason for this is, every browser is internally defined with a fix interval for which it can execute script. When any script executes for more that defined interval such error is thrown.
  • We were expecting to get loading image when Generate button is clicked but unfortunately it won’t happen either. In current case, thread which is responsible for execution of long running script is also responsible for rendering of UI. As the thread is busy with execution of script, UI changes won’t get rendered hence image won’t get displayed unless execution of script completes.

 

Step 8: Start with Web Worker

Now in order to work with Web Worker, first we have to move long running code into a separate JavaScript file. So create a new JavaScript file called MyWebWorker.js and put following code inside it.

var j = 0;
onmessage = function (e)
{ 
};

In above code variable onmessage is a global variable given by Web Worker which will point to a function containing long running script

 

Step 9: Move long running code to Web Worker file

Now before we perform this step, we have to understand two limitations of Web Worker.

  1. Inside Web Worker code, we cannot have any references to DOM elements.
  2. Inside Web Worker code, we cannot use any third party library functionality like jQuery.

After considering above two limitations, Web Worker code will be rewritten as follows.

var j = 0;
onmessage = function (e) {
    for (i = 0; i<= e.data; i++) {

        j = j+i;

    }

  postMessage(j);

};

In the above code call to postMessage function send back final response to the caller. If you are confused, be relax and continue with lab and I will promise that at the end will be simple for you.

 

Step10: Invoke Web Worker

Open WebWorker.html file and change Generate function as follows.

function Generate()
{
    $('#divData').html("Generating");
    $('.MyLoading').show();
    var c = new Worker("MyWebWorker.js");
    c.onmessage = function (e)
    {
        $('#divData').html("Result is " + e.data);
        $('.MyLoading').hide();
    };
    c.postMessage(parseInt($('#myText').val()));
}

As you can see in the place we have created an instance of Worker which is a part of HTML 5 specification. It exposes two major things.

  • postMessage function, which is an indication to worker to start the work in another thread. It simply make a call to onMesssage function in Worker file.
  • onMessage property, which is simply a functional pointer given by web worker. It act as a callback function. It will get executed once worker thread completes its execution. In simple words, postMessage function in a worker file calls this method.

Step 11: Execute and Test

Press F5 and execute the application.

 

Let’s understand the complete code flow.

 

 

Lab 23 – Web Worker with Web API

Web API is an Asp.Net technology for creating REST based services. You can learn more about it from here.

You may be wondering what’s so special about this lab.

You might have worked with REST services 100 times prior.

As you know Service is a server side concept whereas HTML & JavaScript are a client side concepts. To invoke server side functionality from client side we use AJAX. In market tons of third party libraries are available which will make Ajax calls easy for us. Libraries like jQuery, Angular etc.

So what’s the problem? Problem is, as I said before, Web Worker won’t allow use any third party library inside it. In simple words we cannot use jQuery or any other library functionality inside our MyWebWorker.js.

 

Let’s do a small lab and understand how to do it.

Step 1:  Download the Web API

Download the sample Web API project attached with this article.

 

Step 2: Execute the Web API

Open Web API project in visual studio, press F5 and execute it. Navigate to Api as shown in the figure.

 

(Different browsers may display Web API response in different style. In IE you may find a text file downloaded with Json data.)

 

Step 3: Invoke Web API and return data

Create a new MyWebWorker.js to follows.

var j = 0;

onmessage = function (e) {

  var a = new XMLHttpRequest();
  a.onreadystatechange = function () {
    if (a.readyState == 4 &&a.status == 200) {
      postMessage(JSON.parse(a.responseText));
     }
  };
  a.open("get", "http://localhost:35871/api/WorkerTest", false);
  a.send();
};

As you can see, instead of using jQuery we have used pure XmlHttpRequest object to perform Ajax request.

 

Step 4: Change HTML page

Change HTML page content to following

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
        function GetData() {
            $('#divData').html("Generating");
            $('.MyLoading').show();
            var c = new Worker("MyWebWorker.js");
            c.onmessage = function (e) {
                $('#divData').html("Result is " + e.data.CustomerName + "---" + e.data.Address);
                $('.MyLoading').hide();
            };
c.postMessage(parseInt($('#myText').val()));
        }
</script>
</head>
<body>
<input type="button" name="name" value="Generate" />
<span style="color: rgb(17, 17, 17); font-family: 'Segoe UI', Arial, sans-serif; font-size: 14px;"></body>
</html></span>

 

Step 5: Execute and Test

Press F5 and execute the application.

HTML 5 Media

Media is one of the important part in today’s internet world. Everywhere you can see either a video or an audio playing around somewhere on a webpage. Implementing such functionality was really a big pain earlier. We had to rely on Object tag which internally required some third party players like flash. When it comes to devices which don’t have support for flash we end up with nothing. Butnow HTML 5 mad it easy with its new standard video and audio tag.

Lab14 -Working with Video element

In this lab we will understand how to work with new video element in HTML5.

Step 1 – Prepare video

Download a sample video file from somewhere for the demo purpose. If you want you can download it from sample attached.

Step 2 – Create HTML page

Create a new HTML page called Media.html and put following contents inside it

<video controls width="500px" id="vid">
<source src="vid.mp4" />
</video>

You will notice a special attribute called “controls” in the video tag. Adding this attribute simply make control bar in the player visible. Control bar is simple strip normally seen in the bottom section and contain few buttons like “play”, “pause”, “stop” etc.

Note:

  • Please make sure that video and Html file is kept in same directory. In case you want both of them to be placed in different directory, in that case make sure to set the “src” attribute accordingly.
  • HTML 5 video element only supports mp4, webm, 3gpp, m4v, mpeg, ogg, quicktime, x-ms-wmvright now.

Output:

This is how you will get the output.

Lab 15: Scripting with Video element

In this lab we will try to access the video features like play / pause / Stop etc. using JavaScript.

Step 1: Create HTML Page

Create new html page called Media01.html or you can use the same html file used in previous lab. Provide the video source insrc attribute. This time we will not set 'controls' attribute as we will be doing that using JavaScript.

<video width="500px" id="vid">
<source src="vid.mp4" />
</video>

 

Step 2: Add 3 buttons on the same html page for play, stop, end & one input type range element for volume control.

Add the below elements

<input type="button" name="name" value="Play" id="BtnPlay" />
<input type="button" name="name" value="Stop" id="btnStop" />
<input type="button" name="name" value="End" id="btnEnd" />
<input type="range" name="name" value="0.1" min="0" max="1" step="0.1" id="slideVolume" />

 

Step 3: Create JavaScript functions for controlling the video. The below function will helps us to play and pause the video.

function PlayOrPause()
{
var v = document.getElementById('vid');
if (v.paused || v.ended)
{
  v.play();
  document.getElementById('BtnPlay').value = "Pause";
}
else
{
  v.pause();
  document.getElementById('BtnPlay').value = "Play";
}
}

 

Below function will stop the video at the 6th second as we set the currentTime to 6.

function Stop()
{
  var v = document.getElementById('vid');
  v.pause();
  v.currentTime = 6;
  document.getElementById('BtnPlay').value = "Play";
}

 

Below function will end the video and we set the currentTime to duration where duration is the total video time.

function End()
{
  var v = document.getElementById('vid');
  v.pause();
  v.currentTime = v.duration;
  document.getElementById('BtnPlay').value = "Play";
}

 

Below function will set the volume of video player to the range which is between 0 to 1.

function ChangeVolume(element)
{
  var v = document.getElementById('vid');
  v.volume = element.value;//For mute set it to 0
}

 

Output:

 

If you want to show some default image when the player is loaded on pagethen set an attribute called poster with imageurl.

<video controls width="500px" id="vid" poster="MyPoster.jpg">
<source src="vid.mp4" />
</video>

 

Lab 16 - Audio element

Just like video, audio has beenan issue before HTML 5. We didn’t had any option other than relying on object tag and third party libraries. But now HTML 5 Audio element made it easy.

Html5 has provided audio element which can play audio. Lets try it.

Step 1: Prepare audio

Download a sample audio file from somewhere for the demo purpose. If you want, you can download it from sample attached.

Step 2:  Create HTML page

Create a new HTML page called Audio.html and put following contents inside it.

<audio id="audctrl" controls>
<source src="aud.mp3" type="audio/mp3" />
</audio>

Note:

  • Please make sure that audio and Html file is kept in same directory. In case you want both of them to be placed in different directory, in that case make sure to set the “src” attribute accordingly.
  • HTML 5 audio element only supports mp3, wav, ogg format right now.

 

Output:

Lab 17: Scripting with Audio element

In this lab we will try to access the Audio features like play / pause / Stop etc. using JavaScript.

Step 1: Create HTML Page

Create new html page called Auio01.html or you can use the same html file used in previous lab. Provide the audio source in src attribute. This time we will not set controlsattribute as we will be doing that using JavaScript.

<audio id="audctrl">
        <source src="aud.mp3" type="audio/mp3" />
</audio>

 

Step 2: Add 3 buttons on the same html page for play, stop, end & one input type range element for volume control.

Add the below html code 

<innput type="button" name="name" value="Play" id="BtnPlay" />
<input type="button" name="name" value="Stop" id="btnStop" />
<input type="button" name="name" value="End" id="btnEnd" />
<input type="range" name="name" value="0.1" min="0" max="1" step="0.1" id="slideVolume" />

 

Step 3: Create JavaScript functions for controlling the audio. The below function will help us to play and pause the audio

function PlayOrPause()
{
  var v = document.getElementById('audctrl');
  if (v.paused || v.ended)
  {
    v.play();
    document.getElementById('BtnPlay').value = "Pause";
   }
   else
   {
     v.pause();
     document.getElementById('BtnPlay').value = "Play";
   }
}

 

Below function will stop the audio at the 6th second as we set the currentTime to 6.

function Stop()
{
  var v = document.getElementById('audctrl');
  v.pause();
  v.currentTime = 6;
  document.getElementById('BtnPlay').value = "Play";
}

 

Below function will end the audio and we set the currentTime to duration where duration is the total audio time.

function End()
{
  var v = document.getElementById('audctrl');
  v.pause();
  v.currentTime = v.duration;
  document.getElementById('BtnPlay').value = "Play";
}

 

Below function will set the volume of audio player to the range which is between 0 to 1.

function ChangeVolume(element)
{
  varv = document.getElementById('audctrl');
  v.volume = element.value;//For mute set it to 0
}

Output:

Note: You will not see the audio player on the screen.

 

Lab 18 - Drag and Drop Demo

Earlier, for implementing Drag and Drop functionality, developers were used to write their own custom logic or used to take help of some third party libraries. In either case code was not a standard code. Code implemented by one company/developer may be different from another company/developer.  HTML 5 made it easier by introducing a standard APIs for implementing Drag and Drop functionality.

Lets do a small demo and understand how it can be done.

Step 1: Prepare image

Download a sample image file from somewhere for the demo purpose. If you want, you can download it from sample attached.

Step 2: Create HTML file

Create a HTML file say DragDrop.html file. Add the below html content in the file

<div class="fish">
        <img src="fish.png" style="width:179px;height:120px;top:200px;" id="img11" />
 </div>
 <div id="div1" class="bowl">
 </div>

From above code, you can see that I have taken 2 div, one containing <img/> tag with fish as source &  another blank div which will be a destination. I will be applying some css to these div. So adding below css style in a <head/> tag

<style type="text/css">body {
            cursor: pointer;
        }

        .bowl {
            width: 381px;
            height: 388px;
            left: 300px;
            position: absolute;
            top: 10px;
            text-align: center;
            padding-top: 150px;
            float: left;
            background-image: url('bowl.png');
            background-repeat: no-repeat;
        }

        .fish {
            float: left;
            width: 200px;
            height: 200px;
            top: 200px;
            position: absolute;
        }</style><style>
        body {
            cursor: pointer;
        }

        .bowl {
            width: 381px;
            height: 388px;
            left: 300px;
            position: absolute;
            top: 10px;
            text-align: center;
            padding-top: 150px;
            float: left;
            background-image: url('bowl.png');
            background-repeat: no-repeat;
        }

        .fish {
            float: left;
            width: 200px;
            height: 200px;
            top: 200px;
            position: absolute;
        }
    </style>

Step 3: Execute & Test

Lets execute & test this code

  

Looks good. Now we will implement our drag & drop functionality.

Step 3:  Set draggable attribute

Set the draggable attribute to true for the image tag <img/>.

<img src="fish.png" style="width:179px;height:120px;top:200px;" draggable="true" id="img11" />

I set this attribute, because I want to drag this fish in to the bowl.

Step 4: Complete Dragging

Anything which is dragged needs to be dropped somewhere in a container, and in our case drop will happen on a div.( i.e - bowl)

<div id="div1" class="bowl" ondrop="drop(event)"></div>

Add the below javascript function on the same page.

function drop(ev) {
    ev.target.appendChild(document.getElementById("img11"));
}

I am implementing onDrop event which will specify me what should be happen on drop. You can see I am appending the fish image in target element i.e.- bowl
Ondrop event will get called automatically when you leave the mouse from dragged element.

Step 5: Implement OnDragOver event

Now there is a small problem, you will still not be able to drop the fish. The reason is, by default  html container elements wont allow anything to be dragged inside it. So to drop my fish, we must override the default behaviour of that element. This could be done by calling ev.preventDefault() method.

So attach onDragOver event to the destination element i.e- our bowl div and copy the below javascript fuction as well.

<div id="div1" class="bowl" ondrop="drop(event)" ondragover="allowDrop(event)"></div

Copy the Javascript function

function allowDrop(e){
   e.preventDefault();
}

 

Step 6: Execute & test

Select a fish with a mouse and drag it towards a bowl & drop it(leave the mouse).

Output:

                                    

Isn’t it cool and simple ☻ ?

 

Lab 20 -Geo-Location

What is Geo-location?

Geo-location API in HTML 5 lets you to share your location via website. Longitude & latitude can be captured from JavaScript, which in turn can be sent to server and locate it on google maps.

Where it is helpful?

As it can capture your accurate latitude, longitude, altitude, speed, timestamp. So for getting your location’s weather, traffic, or nearby spots and many more, it will be very helpful.

What about privacy if it accesses my location?

The problem with geolocation API is, it could break the security if user is tracked directly from browser. Since it is about compromising user’s privacy, the position is not available unless user accepts it in the browser. User can remain in control as a popup occurs as shown below

This is specifically for internet browser. For other browser the popup may differ. It also specifies which website wants to track your physical location. You can decide whether to give access or not.

Note: This functionality works only in latest browsers like IE 9+, Chrome 5.0+, Firefox 3.5+ and mobile device with Android2.0+, IPhone3.0+

I want to know the latitude & longitude of place from where I am accessing my laptop.

Let’s do a small lab and understand it better.

Initial Setup

Step 1: Create a html page

Create a html page with name Geolocation.html

Step 2: Take a label and a button on the page.

Copy the html code.

<input type="button" value="Get My Location" />
<span id="lblDisplay"></span>

As you can see, I have only one button & a span element. our goal is to display current position in a span on click of a button.

Step 3: Handle button click event

Copy the below javascript code

JavaScript Code

<script type="text/Javascript">
var x = document.getElementById("lblDisplay");

function getLocation() {
  document.getElementById("header").value = "Static Location";
   if (navigator.geolocation) {
   
     navigator.geolocation.getCurrentPosition(showPosition);
   } 
   else {
      alert('No support for geolocation');
   }
}
        
function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
            "Longitude: " + position.coords.longitude;
}

</script>

Explanation:

  • I have created a function getLocation() which will find my current position.
    First of all this api is available using window.navigator.geolocation object.As we are asking for current position so it can get the current position from getCurrentPosition() method.
    This method accept parameter as Position callback which is in our case showPosition() method. This method has an argument which is a position object. This argument allows you to retrieve the latitude and longitude of my location.

Step 4: Execute and Test

Once you run your webpage, a popup will appear which state whether you wish to share your location or not. Click on 'Allow Once'. Then click on "Get My Location" button.

Output:

Seems it is working fine.

Note: Better check the output in Internet Explorer 9+

Step 5: Handling Error

To Handle errors we can pass the second parameter of GetPosition function which we have created earlier.

var x = document.getElementById("lblDisplay"); 

function getLocation() { 
   document.getElementById("header").value = "Static Location";
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition, errorCallBack); 
   }  
 else { 
    alert('No support for geolocation'); 
 } 
}    

function errorCallBack(e) {
            switch (e) {
                case e.PERMISSION_DENIED:
                    x.innerHTML = "User denied geolocation request";
                    break;
                case e.POSITION_UNAVAILABLE:
                    x.innerHTML = "No position information available";
                    break;
                case e.TIMEOUT:
                    x.innerHTML = "Timeout occured";
                    break;
                case e.UNKNOWN_ERROR:
                    x.innerHTML = "Unknown error";
                    break;
            }
        }

As you can see, second parameter is a call back function which will get invoked in case of error.

Explanation:

The second optional parameter ingetCurrentPosition() method is PositionError callback i.e. – errorCallBack(). This method has an argument which is a PositionError object. If you see above in code snippet, I have written a case to handle each type of error.
 

How to update location automatically when location changes?

Initial Setup

Step1: Take a button & a label on the page.

<input type="button" value="Get My Location Updated" />

Step 2: Write a JavaScript function

varwatchid;
function getUpdatedLocation() {
  document.getElementById("header").value = "Dynamic Location";
  if (navigator.geolocation) {
    watchid = navigator.geolocation.watchPosition(showPosition, errorCallBack);
  } 
  else {
                // no native support; maybe try a fallback?
  }
}

Explanation:

navigator.geolocation.watchPosition() : This method return the current position and keeps listening to geolocation and updating the position based on the users moves. It is similar to your GPS system.

Step 3: Execute & Test

To test your output, click on button from one location & move your laptop to different location. You will see the updated latitude & longitude on the screen. This is because the navigator.geolocation.watchPosition() method continuously kepp track of change in latitude & longitude.

 

Lab 21– Geo location with Google Map

Another interesting thing we can do with GeoLocation is we can display the resilts in Map. In order to achive this we will be required access to some Map services like Google Maps.

I am going to use geolocation API to get the position and will use the co-ordinates to map it will google maps to get the direction of some place.

Initial Setup

Step 1: Create a html page 

Create a html page with name Geolocation2.html.

Step 2: Add google map API

Add reference to google map API JavaScript file in your head section of html file.

<script src="http://maps.google.se/maps/api/js?sensor=false"></script>

Step 3: Add html contents

Add a div element to load the map, a button & a textbox for entering the destination. ON click of button, we will load the map with direction from my currect location.

<div id="divmap" style="border:1px solid #ffd800;width:400px;height:400px;"></div>
<input type="text" id="txtDestination" value="Delhi" /> 
<input type="button" value="Get Direction" />

Step 4: Handle button click event

Add a javascript function GetMyDirection() and call it on click event of button Copy the below javascript code

<script type="text/javascript">

function GetMyDirection() {
      if (navigator.geolocation) {

       navigator.geolocation.getCurrentPosition(showPosition, errorCallBack);
      } 
      else {
          alert('No support for geolocation');            
      }
}

function showPosition(position) {
  showInMap(position.coords.latitude, position.coords.longitude);
}

function showInMap(lat, lang) {

  vardirectionsService = new google.maps.DirectionsService();
  vardirectionsRenderer = new google.maps.DirectionsRenderer();

  var route = {
                origin: new google.maps.LatLng(lat, lang),
                destination: document.getElementById('txtDestination').value, travelMode: google.maps.DirectionsTravelMode.DRIVING
   };

 varmapOptions = {
                zoom: 10,
                center: new google.maps.LatLng(50.8504500, 4.3487800),mapTypeId: google.maps.MapTypeId.ROADMAP
 };

  var map = new google.maps.Map(document.getElementById("divmap"), mapOptions);
  directionsRenderer.setMap(map);
  directionsRenderer.setPanel(document.getElementById("divDriveDirection"));
  directionsService.route(route, function (result, status) {
  if (status === google.maps.DirectionsStatus.OK) {
      directionsRenderer.setDirections(result);
  }
  });
}

function errorCallBack(e) {
            switch (e) {
                case e.PERMISSION_DENIED:
                x.innerHTML = "User denied geolocation request";
                    break;
                case e.POSITION_UNAVAILABLE:
                x.innerHTML = "No position information available";
                    break;
                case e.TIMEOUT:
                x.innerHTML = "Timeout occured";
                    break;
                case e.UNKNOWN_ERROR:
                 x.innerHTML = "Unknown error";
                    break;
            }
}
</script>

Explanation:

On callback method of navigator.geolocation.getCurrentPosition() i.e. – showPosition() We called another method which will help to longitude & latitude on google map.

  • Create an object of google map direction service.
vardirectionsService = new google.maps.DirectionsService();
  • Create an object of google direction renderer which will help to render the direction on google map.
vardirectionsRenderer = new google.maps.DirectionsRenderer();
  • Set some route options
var route = {
             origin: new google.maps.LatLng(lat, long),
             destination: document.getElementById('txtDestination').value;              
             travelMode: google.maps.DirectionsTravelMode.DRIVING
         };

origin – Origin is my location so setting google map’s LatLng() method

desitnation – Whatever entered in a tetbox e.g – delhi

travelMode – Specifies mode of travel

  • Set some mapOptions
varmapOptions = {
                zoom: 30,
                center: new google.maps.LatLng(20, 77),
                mapTypeId: google.maps.MapTypeId.ROADMAP
         };

zoom – Specifies the default zoom

center- Specifies where to center the map

maptypeId – As we have selected DRIVING, so show the roads as type

  • Finally create a map
var map = new google.maps.Map(document.getElementById("divmap"), mapOptions);
directionsRenderer.setMap(map);   
directionsService.route(route, function (result, status) {
      if (status === google.maps.DirectionsStatus.OK) {
           directionsRenderer.setDirections(result);
      }
});

 

  • Show all the details about the route and direction to reach the destination from origin using below line
directionsRenderer.setPanel(document.getElementById("divDriveDirection"));

Step 5: Execute & test

Enter some location in textbox & click on button

Output:

You will find the direction is displayed on a map along with route detail to reach entered destination.

Let’s party

Hope you enjoyed Day 2. Please stay tuned for Day 3. Don’t forget to leave your thoughts and suggestions in the form of comments. Your suggestions will be valuable to us.

In case of any training requirement free to connect me at SukeshMarla@Gmail.com & Pradeepsh824@gmail.com

Stay tuned about new updates by connecting me on twitter or Facebook

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Authors

Marla Sukesh
Instructor / Trainer Train IT
India India
Learning is fun but teaching is awesome.

Code re-usability is my passion ,Teaching and learning is my hobby, Becoming an successful entrepreneur is my goal.

By profession I am a Corporate Trainer.
I do trainings on WCF, MVC, Business Intelligence, Design Patterns, HTML 5, jQuery, JSON and many more Microsoft and non-Micrsoft technologiees.

Find my profile here



My sites



@Twitter
@Facebook

Pradeep Shet
Team Leader
India India
I am having 8+ year of Experience in microsoft technology like Asp.Net, WCF, MVC, MSSQL, Silverlight, LINQ, Angular, Knockout, Design Pattern, DI, Oracle, HTML5, CSS3, SAAS, Bootstrap & jquery. I am good in Object Oriented Programming. I am also a MCTS certified.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionI can't get any of this to work Pin
Member 1174085510-May-16 22:19
memberMember 1174085510-May-16 22:19 
QuestionPostMessage Pin
tokano3-May-16 18:56
membertokano3-May-16 18:56 
QuestionHow is the Geo-location works? Pin
Cheung Tat Ming28-Apr-16 16:41
memberCheung Tat Ming28-Apr-16 16:41 
AnswerRe: How is the Geo-location works? Pin
Pradeep Shet1-May-16 9:08
memberPradeep Shet1-May-16 9:08 
PraiseVery Good & easy understand article! Pin
Cheung Tat Ming28-Apr-16 16:37
memberCheung Tat Ming28-Apr-16 16:37 
GeneralRe: Very Good & easy understand article! Pin
Pradeep Shet1-May-16 9:09
memberPradeep Shet1-May-16 9:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180515.1 | Last Updated 4 May 2016
Article Copyright 2016 by Marla Sukesh, Pradeep Shet
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid