8

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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user1901860
  • 101
  • 1
  • 1
  • 3
  • 3
    Welcome to StackOverflow! You're going to have to provide much more detail in order for us to provide any kind of help. What kind of data are you dealing with? What have you tried (specifically, what kind of code have you written)? – Andrew Whitaker Dec 22 '12 at 01:22
  • 1
    For anyone looking for a performant solution to this, I would recommend using the [Haversine formula](https://en.wikipedia.org/wiki/Haversine_formula) to calculate the distance between two locations for which you know the latitude and longitude. The solutions below which use the Google Directions API a) will not return the correct answer in some cases as driving distance might not be the same as actual distance and b) calling the Directions API can take a second or so. Also, c) since Maps changed their pricing policy, it could cost actual money.. – stuartd Dec 04 '18 at 10:20

5 Answers5

18

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.

ScottishTapWater
  • 3,656
  • 4
  • 38
  • 81
sajanyamaha
  • 3,119
  • 2
  • 26
  • 44
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.

James
  • 80,725
  • 18
  • 167
  • 237
1

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;
    }
Skorpi76
  • 11
  • 2
0

Send a request to the Distance Matrix service or to the Directions-Service (when you need the distance of a route)

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
0

And I did this: but it return an empty string. url = "http://maps.googleapis.com/maps/api/directions/json?origin=3320, rue de verdun, verdun&destination=379, 19e avenue, La Guadeloupe, G0M 1G0&sensor=false"

public string fileGetContents(string url)
    {
        string text = "";
        var webRequest = HttpWebRequest.Create(url);
        IAsyncResult asyncResult = null; 
        asyncResult = webRequest.BeginGetResponse(
            state => 
            { 
                var response = webRequest.EndGetResponse(asyncResult); 
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    text = sr.ReadToEnd();
                } 
            }, null
            );
        return text;
    }
user1901860
  • 101
  • 1
  • 1
  • 3