/// <summary> /// Adds a distance instance to the distances list in the DataSource /// </summary> /// <param name="distance"></param> public void AddDistance(DistanceStruct distance) { if (IsDistanceExist(distance) == true) { return; } m_xamlImp.AddDistance(distance); }
/// <summary> /// Calculates distance between two address using Google Maps API. Returns -2 if no internet connection was found /// </summary> /// <param name="originAddress">Origin address</param> /// <param name="destinationAddress">Destination address</param> /// <returns></returns> public static double CalculateDistanceGoogle(AddressStruct originAddress, AddressStruct destinationAddress) { if (BlValidations.CheckForInternetConnection() == false) { return(-2); } Thread.Sleep(100);//Prevents continious requests double distanceInKm = 100.00001; string drivingTime; string url = @"https://maps.googleapis.com/maps/api/distancematrix/xml?units=imperial" + "&origins=" + originAddress.ToString() + "&destinations=" + destinationAddress.ToString() + "&key=AIzaSyADtzLMIItcgU6_9jSifNHC8oMmDN6bpdA"; //request from Google Distance Matrix API service the distance between the 2 addresses HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader sreader = new StreamReader(dataStream); string responsereader = sreader.ReadToEnd(); response.Close(); //the response is given in an XML format XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(responsereader); //If we have an answer if (xmldoc.GetElementsByTagName("status")[0].ChildNodes[0].InnerText == "OK") { //If one of the addresses is not found if (xmldoc.GetElementsByTagName("status")[1].ChildNodes[0].InnerText == "NOT_FOUND") { Console.WriteLine("one of the adrresses is not found"); } //if 2 of the addresses are found else { //the returned distance XmlNodeList distanceXml = xmldoc.GetElementsByTagName("distance"); double distanceInMiles = Convert.ToDouble(distanceXml[0].ChildNodes[1].InnerText.Replace(" mi", "")); distanceInKm = distanceInMiles * 1.609344; m_xamlImp.AddDistance(new DistanceStruct(originAddress, destinationAddress, distanceInKm)); //the returned duration XmlNodeList duration = xmldoc.GetElementsByTagName("duration"); string dur = duration[0].ChildNodes[1].InnerText; drivingTime = dur; } } //we have no answer, the web is busy, the waiting time for answer is limited (QUERY_OVER_LIMIT), we should try again (at least 2 seconds between 2 requests) else { Console.WriteLine("We have'nt got an answer, maybe the net is busy..."); } return(distanceInKm); }