Sunday, 22 December 2013

Get distance between two points using Google API

The following code uses Google API to get distance between two latitude/longitudes.

 static void getGoogleDistance(Args _args)  
 {  
   System.Net.HttpWebRequest  request = null;  
   System.Net.HttpWebResponse response = null;  
   System.IO.Stream      stream = null;  
   System.IO.StreamReader   streamReader = null;  
     
   LogisticsAddressLatitude  fromLatitude, toLatitude;  
   LogisticsAddressLongitude  fromLongitude, toLongitude;  
   
   CLRObject          clro = null;  
   
   real            distance;  
   str             baseUrl, url, xml, disStr;  
   
   XmlDocument         xmlDoc;  
   XmlNodeList         xmlNodes;  
   XmlNode           xmlNode;  
   
   baseUrl = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=%1,%2&destinations=%3,%4&mode=Car&language=gb-en&sensor=false&units=imperial";  
   new InteropPermission(InteropKind::ClrInterop).assert();  
     
   // London  
   fromLatitude = 51.5072;  
   fromLongitude = -0.1275;  
     
   // Manchester  
   toLatitude = 53.4667;  
   toLongitude = -2.2333;  
   
   try  
   {  
     distance = 0;  
   
     url = strFmt(baseUrl, fromLatitude, fromLongitude, toLatitude, toLongitude);  
   
     clro = System.Net.WebRequest::Create(url);  
     request = clro;  
     response = request.GetResponse();  
   
     stream = response.GetResponseStream();  
     streamReader = new System.IO.StreamReader(stream);  
     xml = streamReader.ReadToEnd();  
   
     xmlDoc = XmlDocument::newXml(xml);  
     xmlNodes = xmlDoc.selectNodes('//DistanceMatrixResponse//row//element//distance//text');  
     xmlNode = xmlNodes.nextNode();  
     disStr = strRem(xmlNode.innerText(), ' mi');  
   
     if(disStr != '')  
     {  
       distance = str2num(disStr);  
     }  
   }  
   catch  
   {  
     Global::exceptionTextFallThrough();  
   }  
   CodeAccessPermission::revertAssert();  
   
   info(strFmt('Distance: %1', distance));  
 }  

This posting is provided "AS IS" with no warranties. Use code at your own risk.

No comments:

Post a Comment