Saturday, November 17, 2012

Asp.net - Google Map V3 Directions in Asp.net

In this article i will show you how to provide direction for any given locations on google map in ASP.net.

In this Example not only handles display of the polyline and any associated markers, but also can handle the textual display of directions as a series of steps. 

Let See how to bind Direction routes in Google Map.

Step 1
Download JQuery Script from the following Link
JQuery 1.8.2 

Step 2
Create a Web Application and give the Solution name as SolGoogleMap_Directions.

Step 3
First we need to design a page,it is look like this 
<body>
    <form id="form1" runat="server">
    <div>
        <table border="0" cellspacing="5" cellpadding="5" align="center" width="100%">
            <tr>
                <td style="width: 20%" align="center" valign="middle">From</td>
                <td style="width: 80%">
                    <asp:TextBox ID="txtFrom" runat="server" Width="400px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td style="width: 20%" align="center" valign="middle">To</td>
                <td style="width: 80%">
                    <asp:TextBox ID="txtTo" runat="server" Width="400px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td style="width: 20%">
                    
                </td>
                <td style="width: 80%">
                    <asp:Button ID="btnDirections" runat="server" Text="Direction" Width="200px"/>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="height:100%">

                    <table border="0" cellspacing="2" cellpadding="2" align="center" width="100%">
                        <tr>
                            <td style="width:40%">
                                <div id ="DivDirectionRouteStatus" style="height:480px;overflow: auto"></div>
                            </td>
                            <td style="width:60%">
                                 <div id ="DivGoogleMapCanvas"  style="height:480px;"></div>
                            </td>
                        </tr>
                    </table>

                </td>
            </tr>
        </table>
    </div>
    </form>
</body>


Click on Image for better view

Step 4
Add jQuery file Reference inside the head tag of the page,it is look like this
<script language="javascript" type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>


Step 5
We need to add Google Map V3 API reference in head tag,it is look like this
<script language="javascript" type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU"></script>


Step 6
Bind Location to the text boxes,here we have use google API to have an autocomplete for location,it is look like this  

<script language="javascript" type="text/javascript">

          $(document).ready(function () {

              try
              {
                  var FromAutoComplete = new google.maps.places.Autocomplete($("#txtFrom")[0], {});
                  var ToAutoComplete = new google.maps.places.Autocomplete($("#txtTo")[0], {});

                  google.maps.event.addListener(FromAutoComplete, 'place_changed', function () {
                      var place = FromAutoComplete.getPlace();
                  });

                  google.maps.event.addListener(ToAutoComplete, 'place_changed', function () {
                      var place = ToAutoComplete.getPlace();
                  });
              }
              catch (E)
              {
                  alert(E.message);
              }

             
          });

      </script>


From Location 

To Location

Click on Image for better view

Step 7

Now Initialize Google Map on body onload event,it is look like this.First write script to initialize Google map. 
<script language="javascript" type="text/javascript">

            var DirectionsDisplay;
            var DirectionsService = new google.maps.DirectionsService();

            function InitializeGoogleMap() {

                try
                {
                    DirectionsDisplay = new google.maps.DirectionsRenderer();
                    var LatitudeLongitude = new google.maps.LatLng(19.1969813, 72.9962491);
                    var GoogleMapOptions =
                    {
                        zoom: 10,
                        center: LatitudeLongitude,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };
                    var map = new google.maps.Map($("#DivGoogleMapCanvas")[0], GoogleMapOptions);

                    DirectionsDisplay.setMap(map);
                    DirectionsDisplay.setPanel($("#DivDirectionRouteStatus")[0]);
                }
                catch (E)
                {
                    alert(E.message);
                }

               

            }

 </script>


Then call InitializeGoogleMap function on body onload event,it is look like this
<body onload="InitializeGoogleMap(); return false">



Click on Image for better view

Step 8
Display Direction routes from given location,it is look like this
function GetDirectionRoute() {

                try
                {
                    if ($("#txtFrom").val().length != 0 && $("#txtTo").val().length != 0) {
                    
                        var From =$("#txtFrom").val();
                        var To = $("#txtTo").val();
                        var Request = {
                            origin: From,
                            destination: To,
                            travelMode: google.maps.DirectionsTravelMode.DRIVING
                        };
                        DirectionsService.route(Request, function (response, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                                DirectionsDisplay.setDirections(response);
                            }
                        });
                    }
                    else {
                        if ($("#txtFrom").val().length == 0) {
                            alert("Enter From Location");
                        }
                        else if ($("#txtTo").val().length == 0) {
                            alert("Enter To Location");
                        }
                    }
                }
                catch (E)
                {
                    alert(E.message);
                }

            }


Then call GetDirectionRoute function on btnDirections onclientclick event,it is look like this



Full Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Google Map Version 3 Directions</title>

    <script language="javascript" type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>

     <script language="javascript" type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU"></script>
        
      <script language="javascript" type="text/javascript">

          $(document).ready(function () {

              try
              {
                  var FromAutoComplete = new google.maps.places.Autocomplete($("#txtFrom")[0], {});
                  var ToAutoComplete = new google.maps.places.Autocomplete($("#txtTo")[0], {});

                  google.maps.event.addListener(FromAutoComplete, 'place_changed', function () {
                      var place = FromAutoComplete.getPlace();
                  });

                  google.maps.event.addListener(ToAutoComplete, 'place_changed', function () {
                      var place = ToAutoComplete.getPlace();
                  });
              }
              catch (E)
              {
                  alert(E.message);
              }

             
          });

      </script>

      <script language="javascript" type="text/javascript">

            var DirectionsDisplay;
            var DirectionsService = new google.maps.DirectionsService();

            function InitializeGoogleMap() {

                try
                {
                    DirectionsDisplay = new google.maps.DirectionsRenderer();
                    var LatitudeLongitude = new google.maps.LatLng(19.1969813, 72.9962491);
                    var GoogleMapOptions =
                    {
                        zoom: 10,
                        center: LatitudeLongitude,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };
                    var map = new google.maps.Map($("#DivGoogleMapCanvas")[0], GoogleMapOptions);

                    DirectionsDisplay.setMap(map);
                    DirectionsDisplay.setPanel($("#DivDirectionRouteStatus")[0]);
                }
                catch (E)
                {
                    alert(E.message);
                }

               

            }

            function GetDirectionRoute() {

                try
                {
                    if ($("#txtFrom").val().length != 0 && $("#txtTo").val().length != 0) {
                    
                        var From =$("#txtFrom").val();
                        var To = $("#txtTo").val();
                        var Request = {
                            origin: From,
                            destination: To,
                            travelMode: google.maps.DirectionsTravelMode.DRIVING
                        };
                        DirectionsService.route(Request, function (response, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                                DirectionsDisplay.setDirections(response);
                            }
                        });
                    }
                    else {
                        if ($("#txtFrom").val().length == 0) {
                            alert("Enter From Location");
                        }
                        else if ($("#txtTo").val().length == 0) {
                            alert("Enter To Location");
                        }
                    }
                }
                catch (E)
                {
                    alert(E.message);
                }

            }

        </script>

</head>
<body onload="InitializeGoogleMap(); return false">
    <form id="form1" runat="server">
    <div>
        <table border="0" cellspacing="5" cellpadding="5" align="center" width="100%">
            <tr>
                <td style="width: 20%" align="center" valign="middle">From</td>
                <td style="width: 80%">
                    <asp:TextBox ID="txtFrom" runat="server" Width="400px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td style="width: 20%" align="center" valign="middle">To</td>
                <td style="width: 80%">
                    <asp:TextBox ID="txtTo" runat="server" Width="400px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td style="width: 20%">
                    
                </td>
                <td style="width: 80%">
                    <asp:Button ID="btnDirections" runat="server" Text="Direction" Width="200px" OnClientClick="GetDirectionRoute(); return false" />
                </td>
            </tr>
            <tr>
                <td colspan="2" style="height:100%">

                    <table border="0" cellspacing="2" cellpadding="2" align="center" width="100%">
                        <tr>
                            <td style="width:40%">
                                <div id ="DivDirectionRouteStatus" style="height:480px;overflow: auto"></div>
                            </td>
                            <td style="width:60%">
                                 <div id ="DivGoogleMapCanvas"  style="height:480px;"></div>
                            </td>
                        </tr>
                    </table>

                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


Run the Project.

Output

Click on Image for better view

Download
Download Source Code

11 comments: