Surendra Sharma

Surendra Sharma

Search This Blog

Tuesday, August 13, 2013

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

        
For displaying directions first identify 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:-

Webpage should display direction map from Red Fort to Tajmahal as below




How to do this in ASP.NET?

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

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 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]

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

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

·         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 as

directionsService.route({
    'origin': sourceLatLng,
    'destination': destinationLatLng,
    'travelMode': 'DRIVING'
},
    function(directions, status) {
        directionsRenderer.setDirections(directions);
    }
);

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


ASPX

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Google Map</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">

        $(document).ready(function() {

            directionsService = new google.maps.DirectionsService();

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

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

            //set the map options
            var mapOptions = {
                zoom: 15,
                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) {
                    directionsRenderer.setDirections(directions);
                }
            );

        });

    </script>

</head>
<body>
    <form id="form1" runat="server">
        <div id="map_canvas" style="width: 900px; height: 600px;">
        </div>
    </form>
</body>
</html>

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

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



Monday, August 12, 2013

Delete records by joining table in SQL Server

I want to DELETE some of my records from main table if their entries are available in another table. How can we do it?

Suppose we have two table TableB and TableC

If we found any entry in TableC then delete corresponding records from TableB.


TableB contains 100 records as

SELECT * FROM TableB

 



TableC contains 5 records as

SELECT * FROM TableC



One way of deleting records from TableB is by using IN clause as
DELETE FROM TableB WHERE ID IN (SELECT TableID FROM TableC)

IN clause query delete records successfully but remembers that IN clause is slower than JOINS.


How can we do it using JOINS?

I tried following query first as

DELETE FROM TableB b INNER JOIN TableC c on b.id = c.bid

I received syntax error as below

 


Correct query is

DELETE FROM b FROM TableB b INNER JOIN TableC c on b.id = c.id

Now if I check TableB, I am getting 95 records


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

Friday, August 9, 2013

How to show Info pop up window on Google maps in ASP.NET

Solution:-

I received some comments requesting for how to show pop up info window on click of some latitude and longitude position on Google Map in ASP.NET webform.

Latitude and longitude, showing image on google maps are necessary base part of displaying Info window. So some points in this article are refered from my previous two article How to show any place by latitude and longitude in ASP.NET and How to show your photo at any particular position on Google maps in ASP.NET , but still I am rewriting all the points once again for showing image and info window, so that anybody don’t need to visit to that article.

However I am avoiding database related code. Assuming we have latitude and longitude with image [Add image in Solution Explorer] and employee information.


UI Design:-
User enter latitude and longitude as below


27.175114, 78.042154 are latitude and longitude of Tajmahal J

Webpage should display Tajmahal on Google Map with image and employee information [marked in red lines] as below


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

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

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

C# Code

·         Create Employee Entity class Get employee information in entity class from database

    public class Employee
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string LogoLink { get; set; }
        public int Age { get; set; }
        public string Website { 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 employee information in entity class from database [Leaving database access part]

Employee objEmployee = new Employee() {
    Name = "Alex",
    Address = "Pune",
    Age = 30,
    LogoLink = "http://dev.windowsphone.com/a/nv/microsoftlogo_91x15.png",
    Website = "http://surendrasharmadotnet.blogspot.in/"
};

·         Convert this employee entity into its JSON representation as below

string jsonEmployeeResponse = Helper.ToJson(objEmployee, 100);

·         Register javascript function by passing this Json string as below


string script = "PushEmployeeData(" + jsonEmployeeResponse + ");";

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

employee = null;
        
function PushEmployeeData(objEmployee) {
     employee = objEmployee;
}

·         Get the latitude and longitude from user or file or database and create one point of this latitude and longitude on map [Like X,Y co-ordinates in graph in mathematics]

myLatLng = new google.maps.LatLng(lat, lng);

·         Store icon path in variable and icon object for map marker image as

myIconSrc = 'SK.ico';
myIcon = new google.maps.MarkerImage(myIconSrc, new google.maps.Size(62, 62), null, new google.maps.Point(0, 62));

·         Create HTML to show employee info in info popup window, sreate one DIV and assign all required info as below

var infoWindowText = ''
+ '<div style="border: thin solid #000000; font-family: Verdana; font-size: small;background-color:lightblue"> '
+ '<span style="color:red"> Name :' + employee.Name + '</span><br> Current Address : '
+ employee.Address + '<br /> Age : '
+ employee.Age + '<br /> My Website : '
+ ((employee.Website != '') ? ('<a href="' + employee.Website + '" class="red" target="_blank">'
+ employee.Website + '</a>') : '')
+ '<br /> Image: <img id="mySnap" alt="Microsoft" src="' + employee.LogoLink + '"/>'
+ '</div>';

·         Create info window object as below

infoWindow = new google.maps.InfoWindow({ disableAutoPan: true });

·         Assign all HTML content to this info window object as

infoWindow.setContent(infoWindowText);

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

·         Attach image on map at the specific location as

marker = new google.maps.Marker({
position: myLatLng,
icon: myIcon,
map: map
});
         
·         Register click event on marker image for calling Info window function so that whenever user click on some latitude and longitude position , show pop up info window on Google Map

google.maps.event.addListener(marker, 'click', function(e) { showInfoWindow() });

·         Function to show info winfow as below

function showInfoWindow() {
    infoWindow.open(map, marker);
}

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

C# Code

public partial class ShowMap : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Employee objEmployee = new Employee()
        {
            Name = "Alex",
            Address = "Pune",
            Age = 30,
            LogoLink = "http://dev.windowsphone.com/a/nv/microsoftlogo_91x15.png",
            Website = "http://surendrasharmadotnet.blogspot.in/"
        };

        string jsonEmployeeResponse = Helper.ToJson(objEmployee, 100);

        string script = "PushEmployeeData(" + jsonEmployeeResponse + ");";

        Helper.BindClientScript(script, this);
    }
}

public class Employee
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string LogoLink { get; set; }
    public int Age { get; set; }
    public string Website { 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

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Google Map</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">

        employee = null;

        function PushEmployeeData(objEmployee) {
            employee = objEmployee;
        }


        $(document).ready(function() {

            $("#btnShow").click(function() {

                myIconSrc = 'SK.ico';
                var lat = document.getElementById("txtLat").value;
                var lng = document.getElementById("txtLng").value;

                myLatLng = new google.maps.LatLng(lat, lng);
                //create the icon object
                myIcon = new google.maps.MarkerImage(myIconSrc, new google.maps.Size(62, 62), null, new google.maps.Point(0, 62));

                var infoWindowText = ''
                + '<div style="border: thin solid #000000; font-family: Verdana; font-size: small;background-color:lightblue"> '
                + '<span style="color:red"> Name :' + employee.Name + '</span><br> Current Address : '
                + employee.Address + '<br /> Age : '
                + employee.Age + '<br /> My Website : '
                + ((employee.Website != '') ? ('<a href="' + employee.Website + '" class="red" target="_blank">'
                + employee.Website + '</a>') : '')
                + '<br /> Image: <img id="mySnap" alt="Microsoft" src="' + employee.LogoLink + '"/>'
                + '</div>';

                infoWindow = new google.maps.InfoWindow({ disableAutoPan: true }); //create the infowindow object
                infoWindow.setContent(infoWindowText);


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

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

                marker = new google.maps.Marker({
                    position: myLatLng,
                    icon: myIcon,
                    map: map
                });

                google.maps.event.addListener(marker, 'click', function(e) { showInfoWindow() });

                return false;
            });
        });

        function showInfoWindow() {
            infoWindow.open(map, marker);
        }
       
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <table width="40%" align="center" style="border: thin solid #000000; font-family: Verdana;
        font-size: small;">
        <tr>
            <td>
                <asp:Label ID="lblLat" runat="server" Text="Enter Latitude"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtLat" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblLng" runat="server" Text="Enter Longitude"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtLng" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Button ID="btnShow" runat="server" Text="Show Place" />
            </td>
        </tr>
    </table>
    <br />
    <table align="center">
        <tr>
            <td>
                <div id="map_canvas" style="width: 700px; height: 500px;">
                </div>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>



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