If you have only two addresses, first try to get local network information using GEOCODING, and then there are many ways to get the distance between them.
OR
if you don't need geocoding and want a CS solution, try this:
public int getDistance(string origin, string destination) { System.Threading.Thread.Sleep(1000); int distance = 0; //string from = origin.Text; //string to = destination.Text; string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false"; string requesturl = url; //string requesturl = @"http://maps.googleapis.com/maps/api/directions/json?origin=" + from + "&alternatives=false&units=imperial&destination=" + to + "&sensor=false"; string content = fileGetContents(requesturl); JObject o = JObject.Parse(content); try { distance = (int)o.SelectToken("routes[0].legs[0].distance.value"); return distance; } catch { return distance; } return distance; //ResultingDistance.Text = distance; } protected string fileGetContents(string fileName) { string sContents = string.Empty; string me = string.Empty; try { if (fileName.ToLower().IndexOf("http:") > -1) { System.Net.WebClient wc = new System.Net.WebClient(); byte[] response = wc.DownloadData(fileName); sContents = System.Text.Encoding.ASCII.GetString(response); } else { System.IO.StreamReader sr = new System.IO.StreamReader(fileName); sContents = sr.ReadToEnd(); sr.Close(); } } catch { sContents = "unable to connect to server "; } return sContents; }
OR
if you donβt want to contact Google and you only need AIR DISTANCE , try this:
public decimal calcDistance(decimal latA, decimal longA, decimal latB, decimal longB) { double theDistance = (Math.Sin(DegreesToRadians(latA)) * Math.Sin(DegreesToRadians(latB)) + Math.Cos(DegreesToRadians(latA)) * Math.Cos(DegreesToRadians(latB)) * Math.Cos(DegreesToRadians(longA - longB))); return Convert.ToDecimal((RadiansToDegrees(Math.Acos(theDistance)))) * 69.09M * 1.6093M; }
NB. Starting June 11, 2018, this approach will no longer work, since Google has disabled keyless access to the Maps API. If you want to use this approach, you need to register on their cloud platform and enable billing.
sajanyamaha
source share