Distance between addresses

24,939

Solution 1

If you just have two addreses first try to get lat lan by GEOCODING and then there are many methods to get distance in between.

OR

if you dont 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 dont want to mess with google and need only 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: As of June 11th 2018 this approach will no longer work as Google has disabled keyless access to the Maps API. If you wish to use this approach you will have to sign up for their cloud platform and enable billing.

Solution 2

You can do this using the Google Directions API, you pass the start/end locations to the API as address strings or coordinates and Google will do all the leg work for you.

Routes are made up of various legs based on how many way points you specify. In your scenario (0 way points) you should only have 1 leg which should have an estimated distance property.

Solution 3

I have fixed the code from the answer above for it to work with google key.

  1. Get you API key for google maps
  2. Install Nuget package: Newtonsoft.Json

3.

 public int getDistance(string origin, string destination)
    {
        System.Threading.Thread.Sleep(1000);
        int distance = 0;
        string key = "YOUR KEY";

        string url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&key=" + key;
        url = url.Replace(" ", "+");          
        string content = fileGetContents(url);      
        JObject o = JObject.Parse(content);
        try
        {
            distance = (int)o.SelectToken("routes[0].legs[0].distance.value");
            return distance;
        }
        catch
        {
            return distance;
        }
    }

    protected string fileGetContents(string fileName)
    {
        string sContents = string.Empty;
        string me = string.Empty;
        try
        {
            if (fileName.ToLower().IndexOf("https:") > -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;
    }
Share:
24,939
user1901860
Author by

user1901860

Updated on July 30, 2022

Comments

  • user1901860
    user1901860 almost 2 years

    Is there a way to have a distance between 2 addresses calculated by Google Maps? How?

  • user1901860
    user1901860 over 11 years
    Where do I get the JObject parser
  • user1901860
    user1901860 over 11 years
    And what is the fileGetContents fonction?
  • user1901860
    user1901860 over 11 years
    I downloaded the JSon linq here: james.newtonking.com/pages/json-net.aspx
  • mark
    mark over 8 years
    @sajanyamaha I have used your code works like a charm however if I give non existant address it still calculates distance and If I check on Google Maps it says 'Could Not find address' how to achieve this. Thanks for the code.
  • ScottishTapWater
    ScottishTapWater over 5 years
    Note this code will no longer work as you now need an API key.
  • Hasher
    Hasher over 2 years
    Whats the purpose of Sleep(1000) here?
  • Hasher
    Hasher over 2 years
    It worked, thanks!. May i ask what for Sleep(1000) is used here?