Surendra Sharma

Surendra Sharma

Search This Blog

Wednesday, August 14, 2013

How to show directions with route details between two locations on Google maps in ASP.NET

         
For displaying directions with route details first we need latitude and longitude of two locations.

To know how to get Latitude and Longitude of any place in Google maps? Please Visit here

Location 1 is act as source point and location 2 is destination point.

I am considering
·         Source Location - 28.67854, 77.23938 - Red Fort, New Delhi, India
·         Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra

UI Design:-

Here is a screenshot of Google map from Red Fort to Tajmahal






We need to develop similar webpage with same details in ASP.NET



How to do this in ASP.NET using C#?

Google team already developed API for map and its functionality. These API works with JQuery or Javascript.

C# Code

·         Create Location Entity class to store Latitude and Longitude

public class LocationInfo
{
    public string Latitude { get; set; }
    public string Longitude { get; set; }
}

·         Create one Helper class for creating JSON string and registering Javascript.
Include namespcase “using System.Web.Script.Serialization;” in your code for  accessing “JavaScriptSerializer” class

public static class Helper
{
    /// <summary>
    /// Generates Json for specific object instance
    /// </summary>
    /// <param name="instance">Instance to be converted to Json </param>
    /// <param name="recursionDepth">Recursion depth optional paramter</param>
    /// <returns>Json for specific object instance</returns>
    public static string ToJson(this object instance, int recursionDepth) {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.RecursionLimit = recursionDepth;
        return serializer.Serialize(instance);
    }

    /// <summary>
    /// Register java script
    /// </summary>
    /// <param name="script"></param>
    /// <param name="control"></param>
    public static void BindClientScript(string script, Control control)
    {
        ScriptManager.RegisterStartupScript(control, typeof(Page), Guid.NewGuid().ToString(), script, true);
    }
}


·         Get source and destination location details in entity class from database [Leaving database access part]

//Source Location - Red Fort, New Delhi, India
LocationInfo sourceLocation = new LocationInfo() { Latitude = "28.67854", Longitude = "77.23938" };

//Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra
LocationInfo destinationLocation = new LocationInfo() { Latitude = "27.175114", Longitude = "78.042154" };

·         Convert this location entities into its JSON representation as below

string jsonSourceResponse = Helper.ToJson(sourceLocation, 100);
string jsonDestinationResponse = Helper.ToJson(destinationLocation, 100);

·         Register javascript function by passing this Json string as below

string script = "PushLocationData(" + jsonSourceResponse + "," + jsonDestinationResponse + ");";

Helper.BindClientScript(script, this);

ASPX

·         First we need two javascript file. You don’t need to download these file

Map functionality - http://maps.google.com/maps/api/js?sensor=false
JQuery - https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js

·         So its declaration in ASPX file is as below

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>     

·         Create javascript function to get the JSON string and hold it in javascript global variable as

source = null;
destination = null;

function PushLocationData(objsource, objdestination) {
    source = objsource;
    destination = objdestination;
}

·         Create google maps direction service object as

directionsService = new google.maps.DirectionsService();

·         Get the latitude and longitude of source and destination location [Like X,Y co-ordinates in graph in mathematics]

sourceLatLng = new google.maps.LatLng(source.Latitude, source.Longitude);

destinationLatLng = new google.maps.LatLng(destination.Latitude, destination.Longitude);

·         Set different option of maps like zoom level, alignment of point in map, map type, navigation control as

var mapOptions = {
                    zoom: 15,
                    center: myLatLng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    navigationControl: true
                };

·         Create map object with all specified optins and show in DIV as below

map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

·         Specify the way you want directions on google maps as below

directionsRenderer = new google.maps.DirectionsRenderer({
    'map': map,
    'draggable': false,
    'hideRouteList': true,
    'suppressMarkers': true
});

·         Draw route from source to destination location  in driving mode on maps. With each route we will get directions informations such as route description, distance, duration etc. as below

directionsService.route({
    'origin': sourceLatLng,
    'destination': destinationLatLng,
    'travelMode': 'DRIVING'
},

    function(directions, status) {
        for (var i = 0; i < directions.routes.length; i++) {
            var thisRoute = directions.routes[i];

            for (var j = 0; j < thisRoute.legs.length; j++) {
                var thisLeg = thisRoute.legs[j];

                var useDistance = thisLeg.distance.text;
                var useDuration = thisLeg.duration.text;

                var directionsHTML = '';
                for (var k = 0; k < thisLeg.steps.length; k++) {
                    var thisStep = thisLeg.steps[k];
                    directionsHTML += '<div>' + (k + 1) + '. ' + thisStep.instructions + '<BR/>-------------------' + thisStep.distance.text + '</div>';
                    directionsHTML += '<div></div>';
                }
                $('#total_distance').html(useDistance);
                $('#total_duration').html(useDuration);
                $('#direction_steps').append(directionsHTML);
            }
        }
        directionsRenderer.setDirections(directions);

    }
);
                            

Here is complete C# code and ASPX. Just copy and paste below code and bingooooo here you go


C# Code

    public partial class GoogleDirections : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Source Location - Red Fort, New Delhi, India
            LocationInfo sourceLocation = new LocationInfo() { Latitude = "28.67854", Longitude = "77.23938" };

            //Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra
            LocationInfo destinationLocation = new LocationInfo() { Latitude = "27.175114", Longitude = "78.042154" };

            string jsonSourceResponse = Helper.ToJson(sourceLocation, 100);
            string jsonDestinationResponse = Helper.ToJson(destinationLocation, 100);

            string script = "PushLocationData(" + jsonSourceResponse + "," + jsonDestinationResponse + ");";
            Helper.BindClientScript(script, this);
        }
    }

    public class LocationInfo
    {
        public string Latitude { get; set; }
        public string Longitude { get; set; }
    }

    public static class Helper
    {
        /// <summary>
        /// Generates Json for specific object instance
        /// </summary>
        /// <param name="instance">Instance to be converted to Json </param>
        /// <param name="recursionDepth">Recursion depth optional paramter</param>
        /// <returns>Json for specific object instance</returns>
        public static string ToJson(this object instance, int recursionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(instance);
        }

        /// <summary>
        /// Register java script
        /// </summary>
        /// <param name="script"></param>
        /// <param name="control"></param>
        public static void BindClientScript(string script, Control control)
        {
            ScriptManager.RegisterStartupScript(control, typeof(Page), Guid.NewGuid().ToString(), script, true);
        }
    }

ASPX


<!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>
    <title>Google Directions with route info</title>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script type="text/javascript">

        source = null;
        destination = null;

        function PushLocationData(objsource, objdestination) {
            source = objsource;
            destination = objdestination;
        }

        $(document).ready(function() {

            directionsService = new google.maps.DirectionsService();

            //Source Location - Red Fort, New Delhi, India
            sourceLatLng = new google.maps.LatLng(source.Latitude, source.Longitude);

            //Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra
            destinationLatLng = new google.maps.LatLng(destination.Latitude, destination.Longitude);

            //set the map options
            var mapOptions = {
                zoom: 20,
                center: destinationLatLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                navigationControl: true
            };

            //create the map object
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            directionsRenderer = new google.maps.DirectionsRenderer({
                'map': map,
                'draggable': false,
                'hideRouteList': true,
                'suppressMarkers': true
            });

            directionsService.route({
                'origin': sourceLatLng,
                'destination': destinationLatLng,
                'travelMode': 'DRIVING'
            },
            function(directions, status) {
                for (var i = 0; i < directions.routes.length; i++) {
                    var thisRoute = directions.routes[i];

                    for (var j = 0; j < thisRoute.legs.length; j++) {
                        var thisLeg = thisRoute.legs[j];

                        var useDistance = thisLeg.distance.text;
                        var useDuration = thisLeg.duration.text;

                        var directionsHTML = '';
                        for (var k = 0; k < thisLeg.steps.length; k++) {
                            var thisStep = thisLeg.steps[k];
                            directionsHTML += '<div>' + (k + 1) + '. ' + thisStep.instructions + '<BR/>-------------------' + thisStep.distance.text + '</div>';
                            directionsHTML += '<div></div>';
                        }
                        $('#total_distance').html(useDistance);
                        $('#total_duration').html(useDuration);
                        $('#direction_steps').append(directionsHTML);
                    }
                }
                directionsRenderer.setDirections(directions);
            });
        });

    </script>

</head>
<body>
    <form id="form1" runat="server">
    <table style="border: thin solid #000000; font-family: Verdana; font-size: small;"
        width="100%">
        <tr>
            <td valign="top" width="40%">
                <div id="direction_steps_holder" style="width: 100%">
                    <div>
                        <b>Directions to TajMahal, Agra (<span id="total_distance"></span> - about <span
                            id="total_duration"></span>) </b>
                    </div>
                    <div id="direction_steps">
                    </div>
                </div>
            </td>
            <td valign="top">
                <div id="map_canvas" style="width: 750px; height: 700px;">
                </div>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>


Similar articles which you may like

Latitude and longitude, showing image, info popup window on google maps are necessary base part of google maps. You can get more info from below articles




Please leave your comments or share this article if it’s useful for you.

1 comment: