How to find distance between two location through Google API's using Asp.Net C#

<%@ 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 id="Head1" runat="server">
    <title>Google Distance Matrix</title>
    <style type="text/css">
        .style1
        {
            height: 30px;
        }
    </style>

    <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"
        type="text/javascript"></script>

    <script type="text/javascript">
        function OrginAutoComplete() {
            try {
                var input = document.getElementById('TextBox1');
                var autocomplete = new google.maps.places.Autocomplete(input);
                autocomplete.setTypes('changetype-geocode');
            }
            catch (err) {
                // alert(err);
            }
        }


        function DestAutoComplete() {
            try {
                var input = document.getElementById('TextBox2');
                var autocomplete = new google.maps.places.Autocomplete(input);
                autocomplete.setTypes('changetype-geocode');
            }
            catch (err) {
                // alert(err);
            }
        }

        google.maps.event.addDomListener(window, 'load', OrginAutoComplete);
        google.maps.event.addDomListener(window, 'load', DestAutoComplete);
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellpadding="0" cellspacing="0" align="center" width="700">
            <tr>
                <td colspan="2" height="40">
                    <b>Distance calculation using Google API</b>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    Enter Orgin Place
                </td>
                <td class="style1">
                    <asp:TextBox ID="TextBox1" runat="server" Width="300"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td height="30">
                    Enter Destination Place
                </td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" Width="300"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center" height="60">
                    <asp:Button ID="btnSearch" runat="server" Text="Calculate Distance" OnClick="btnSearch_Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center" height="40">
                    <br />
                    <br />
                    <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
                </td>
            </tr>
        </table>
        <br />
    </div>
    </form>
</body>
</html>
.......................................code behind..................................................
using System.Net;
using System.Xml;
using System.Data;
using System.IO;
using System.Xml.XPath;
using System;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblResult.Text = "";
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //Declare variable to store XML result
        string xmlResult = null;

        //Pass request to google api with orgin and destination details
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + TextBox1.Text + "&destinations=" + TextBox2.Text + "&mode=Car&language=us-en&sensor=false");

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        //Get response as stream from httpwebresponse
        StreamReader resStream = new StreamReader(response.GetResponseStream());

        //Create instance for xml document
        XmlDocument doc = new XmlDocument();

        //Load response stream in to xml result
        xmlResult = resStream.ReadToEnd();

        //Load xmlResult variable value into xml documnet
        doc.LoadXml(xmlResult);

        string output = "";

        try
        {
            //Get specified element value using select single node method and verify it return OK (success ) or failed
            if (doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/status").InnerText.ToString().ToUpper() != "OK")
            {
                lblResult.Text = "Invalid City Name please try again";
                return;
            }

            //Get DistanceMatrixResponse element and its values
            XmlNodeList xnList = doc.SelectNodes("/DistanceMatrixResponse");
            foreach (XmlNode xn in xnList)
            {
                if (xn["status"].InnerText.ToString() == "OK")
                {
                    //Form a table and bind it orgin, destination place and return distance value, approximate duration
                    output = "<table align='center' width='600' cellpadding='0' cellspacing='0'>";
                    output += "<tr><td height='60' colspan='2' align='center'><b>Travel Details</b></td>";
                    output += "<tr><td height='40' width='30%' align='left'>Orgin Place</td><td align='left'>" + xn["origin_address"].InnerText.ToString() + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Destination Place</td><td align='left'>" + xn["destination_address"].InnerText.ToString() + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Travel Duration (apprx.)</td><td align='left'>" + doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/duration/text").InnerText + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Distance</td><td align='left'>" + doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/distance/text").InnerText + "</td></tr>";
                    output += "</table>";

                    //finally bind it in the result label control
                    lblResult.Text = output;
                }
            }
        }
        catch (Exception ex)
        {
            lblResult.Text = "Error during processing";
            return;
        }
    }
}
Share:

No comments:

Post a Comment

Wednesday, 4 June 2014

How to find distance between two location through Google API's using Asp.Net C#

<%@ 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 id="Head1" runat="server">
    <title>Google Distance Matrix</title>
    <style type="text/css">
        .style1
        {
            height: 30px;
        }
    </style>

    <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"
        type="text/javascript"></script>

    <script type="text/javascript">
        function OrginAutoComplete() {
            try {
                var input = document.getElementById('TextBox1');
                var autocomplete = new google.maps.places.Autocomplete(input);
                autocomplete.setTypes('changetype-geocode');
            }
            catch (err) {
                // alert(err);
            }
        }


        function DestAutoComplete() {
            try {
                var input = document.getElementById('TextBox2');
                var autocomplete = new google.maps.places.Autocomplete(input);
                autocomplete.setTypes('changetype-geocode');
            }
            catch (err) {
                // alert(err);
            }
        }

        google.maps.event.addDomListener(window, 'load', OrginAutoComplete);
        google.maps.event.addDomListener(window, 'load', DestAutoComplete);
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellpadding="0" cellspacing="0" align="center" width="700">
            <tr>
                <td colspan="2" height="40">
                    <b>Distance calculation using Google API</b>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    Enter Orgin Place
                </td>
                <td class="style1">
                    <asp:TextBox ID="TextBox1" runat="server" Width="300"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td height="30">
                    Enter Destination Place
                </td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" Width="300"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center" height="60">
                    <asp:Button ID="btnSearch" runat="server" Text="Calculate Distance" OnClick="btnSearch_Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center" height="40">
                    <br />
                    <br />
                    <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
                </td>
            </tr>
        </table>
        <br />
    </div>
    </form>
</body>
</html>
.......................................code behind..................................................
using System.Net;
using System.Xml;
using System.Data;
using System.IO;
using System.Xml.XPath;
using System;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblResult.Text = "";
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //Declare variable to store XML result
        string xmlResult = null;

        //Pass request to google api with orgin and destination details
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + TextBox1.Text + "&destinations=" + TextBox2.Text + "&mode=Car&language=us-en&sensor=false");

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        //Get response as stream from httpwebresponse
        StreamReader resStream = new StreamReader(response.GetResponseStream());

        //Create instance for xml document
        XmlDocument doc = new XmlDocument();

        //Load response stream in to xml result
        xmlResult = resStream.ReadToEnd();

        //Load xmlResult variable value into xml documnet
        doc.LoadXml(xmlResult);

        string output = "";

        try
        {
            //Get specified element value using select single node method and verify it return OK (success ) or failed
            if (doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/status").InnerText.ToString().ToUpper() != "OK")
            {
                lblResult.Text = "Invalid City Name please try again";
                return;
            }

            //Get DistanceMatrixResponse element and its values
            XmlNodeList xnList = doc.SelectNodes("/DistanceMatrixResponse");
            foreach (XmlNode xn in xnList)
            {
                if (xn["status"].InnerText.ToString() == "OK")
                {
                    //Form a table and bind it orgin, destination place and return distance value, approximate duration
                    output = "<table align='center' width='600' cellpadding='0' cellspacing='0'>";
                    output += "<tr><td height='60' colspan='2' align='center'><b>Travel Details</b></td>";
                    output += "<tr><td height='40' width='30%' align='left'>Orgin Place</td><td align='left'>" + xn["origin_address"].InnerText.ToString() + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Destination Place</td><td align='left'>" + xn["destination_address"].InnerText.ToString() + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Travel Duration (apprx.)</td><td align='left'>" + doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/duration/text").InnerText + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Distance</td><td align='left'>" + doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/distance/text").InnerText + "</td></tr>";
                    output += "</table>";

                    //finally bind it in the result label control
                    lblResult.Text = output;
                }
            }
        }
        catch (Exception ex)
        {
            lblResult.Text = "Error during processing";
            return;
        }
    }
}

No comments:

Post a Comment

Popular

Total Pageviews

Archive