Friday, October 25, 2013

CREATE-REMOVE-ADD IN JSON USING JAVASCRIPT

//CREATING JSON OBJECT
        var Obj = { Languages: [] };

        //ADDING ITEMS TO JSON OBJECT
        Obj.Languages.push({ id: "1", Name: 'C Language' });
        Obj.Languages.push({ id: "2", Name: 'C++ Language' });
        Obj.Languages.push({ id: "3", Name: 'JAVA' });
        Obj.Languages.push({ id: "4", Name: 'JAVASCRIPT' });
        Obj.Languages.push({ id: "5", Name: 'JQUERY' });

        //REMOVING ITEMS FROM JSON OBJECT
        Obj.Languages.pop();

        //REMOVING PARTICULAR ITEM FROM JSON OBJECT
        Obj.Languages.splice(2, 1);

        //ADDING NEW ITEM IN MIDDLE
        //SIGNATURE OF splice(INDEX, COUNT TO DELETE FROM INDEX, JSON OBJECT TO ADD NEW ITEM)
        Obj.Languages.splice(2, 0, { id: 5, Name: 'DOTNET' });

Saturday, October 5, 2013

CALCULATING DISTANCE BETWEEN TWO PLACES ASP.NET

Calculating distance between two places made easy by GOOGLE MAP's DISTANCE MATRIX.  Google Map Matrix is an opensource api which will return Json & Xml as responces for its each request.

Here we can get google map search suggestions too using google map's javascript api.  By this the text box you enter for desired place will show you google map's search suggestions.

Let go to code.

Html in aspx file:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Google Maps</title>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"
        type="text/javascript"></script>
    <script type="text/javascript">
        //for getting origin autocomplete google map results
        function OrginAutoComplete() {
            try {
                var input = document.getElementById('TextBox1');
                var autocomplete = new google.maps.places.Autocomplete(input);
                autocomplete.setTypes('changetype-geocode');
            }
            catch (err) {
                // alert(err);
            }
        }

        //for getting destination autocomplete google map results
        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 in Button Click event:

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;
        }

    }


Let's step into the code

First we need design our aspx page with two text boxes and one button. One for origin, another for destination and button for calculating distance.  In this aspx file we need to refer googles map's javascript api file as follows

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

and after this there are two javascript functions OrginAutoComplete for getting search suggestions for Origin text box and DestAutoComplete for getting search suggestions for destination text box.  After adding these two functions we need to refer these methods for google map's event listeners. Till now we have completed design and search suggestions part of this demo.  Now lets go to code part which comprises of sending origin and destination details as request to google map's api and gathering the response and parsing it for getting the exact distance, time and exact location details.

If you need explanation for the code, just refer the code block you can get a good idea about this by comment lines which i have mentioned for line by line.

Any Queries Kindly let me know.

Happy coding....