Monday, January 10, 2011

Driving directions from Google Maps in XML format

The Google maps return this document in result of Http request sent by the user which contains the data for direction and distance. You will see the implementation and translation when you walk in to the code. Use Linq allows XML data to be queried by using the standard query operators as well as tree-specific operators that provide XPath-like navigation through descendants, ancestors, and siblings. It simplifies working with XML data without having to resort to using additional language syntax like XPath or XQuery. You can use LINQ to XML to perform LINQ queries over XML that you retrieve from the file system, from a remote web service, or from in-memory XML content. 
Coding ::
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Xml;
 XNamespace obj_XNameSpace = XNamespace.Get("http://earth.google.com/kml/2.0");
string Des_Source_URL = "http://maps.google.com/?q=From " + txtDestination.Text + " to " + txtSource.Text + "&output=kml&view=text";
IEnumerable<XElement> nodes = from n in Des_Source_document.Descendants(obj_XNameSpace + "Placemark")    
select n;
var Select_Name_Doc = from n in nodes
where ((from x in n.Descendants(obj_XNameSpace + "name"select x).Count() > 0)
&& ((from y in n.Descendants(obj_XNameSpace + "description")
select y).Count() > 0)

select n;

foreach (var node in Select_Name_Doc)
{
    DataRow dr = obj_datatble.NewRow();
    dr["Value"] = node.Descendants(obj_XNameSpace + "name").First().Value;
    dr["Distance"] = node.Descendants(obj_XNameSpace + "description").First().Value;
    obj_datatble.Rows.Add(dr);
}
GridView1.DataSource = obj_datatble;
GridView1.DataBind();

About the Code ::
1: XNamespace this will works as a namespace for which we will use to parse the KML for the specified Uniform Resource Identifier.
2: Browser Qurey www.maps.google.com/?q=from "from_address" to "to_address" "&output=kml&view=text"; (where "from" and "to" are the keywords).
3: The "output" parameter retrieves the result in the given format which will be KML in this case.
4: 
The Xdocument.Descendants() Returns a collection of the descendant elements for this document or element, in document order.
5: 
After getting all the vlaues in Select_Name_Doc I declare a cusom DataTable with two rows "value" and "distance" and then storing vlaue of each node in these rows and then add in to a DataTable inside foreach loop. After it's done adding the rows, I assigned the DataTable to GridView as  DataSource and then bind the datagrid.





No comments:

Post a Comment