Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Google Maps Distance Matrix API Example C#

The Google Distance Matrix API is a service that provides travel distance and journey duration for a matrix of origins and destinations using a given mode of travel. The following google maps distance matrix API example will demonstrate to you how to calculate the distance between two points using the Google Matrix API in C#.

Note: Route information, including polylines and textual directions, can be obtained by passing the desired single origin and destination to the Directions Service.

Travel Modes

  • BICYCLING requests for bicycling directions via bicycle paths & preferred streets (currently only available in the US and some Canadian cities).
  • DRIVING (default) indicates standard driving directions using the road network.
  • TRANSIT requests directions via public transit routes. This option may only be specified if the request includes an API key. See the section on transit options for the available options in this type of request.
  • WALKING requests walking directions via pedestrian paths & sidewalks (where available).

Google Maps Distance Matrix API Example C#:

You must add an API key from your Google Maps APIs Premium Plan project if you want to include the drivingOptions field in the DistanceMatrixRequest.

using System;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string getJSON = DistanceMatrixRequest("28.994328,77.704871", "29.147364,77.610155");
            Response.Write(getJSON);
        }
    }
    public string DistanceMatrixRequest(string source, string Destination)
    {
        try
        {
            int alongroaddis = Convert.ToInt32(ConfigurationManager.AppSettings["alongroad"].ToString());
            string keyString = ConfigurationManager.AppSettings["keyString"].ToString(); // passing API key
            string clientID = ConfigurationManager.AppSettings["clientID"].ToString(); // passing client id
            string urlRequest = "";
            string travelMode = "Walking"; //Driving, Walking, Bicycling, Transit.
            urlRequest = @"http://maps.googleapis.com/maps/api/distancematrix/json?origins=" + source + "&destinations=" + Destination + "&mode='" + travelMode + "'&sensor=false";
            if (keyString.ToString() != "")
            {
                urlRequest += "&client=" + clientID;
                urlRequest = Sign(urlRequest, keyString); // request with api key and client id
            }
            WebRequest request = WebRequest.Create(urlRequest);
            request.Method = "POST";
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse response = request.GetResponse();
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string resp = reader.ReadToEnd();
            reader.Close();
            dataStream.Close();
            response.Close();
            return resp;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public string Sign(string url, string keyString)
    {
        ASCIIEncoding encoding = new ASCIIEncoding();
        // converting key to bytes will throw an exception, need to replace '-' and '_' characters first.
        string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/");
        byte[] privateKeyBytes = Convert.FromBase64String(usablePrivateKey);
        Uri uri = new Uri(url);
        byte[] encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query);
        // compute the hash
        HMACSHA1 algorithm = new HMACSHA1(privateKeyBytes);
        byte[] hash = algorithm.ComputeHash(encodedPathAndQueryBytes);
        // convert the bytes to string and make url-safe by replacing '+' and '/' characters
        string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_");
        // Add the signature to the existing URI.
        return uri.Scheme + "://" + uri.Host + uri.LocalPath + uri.Query + "&signature=" + signature;
    }
}
Web.config

Download Source Code

References:

    • Distance Matrix Service Documentation
    • Usage and Billing

The post Google Maps Distance Matrix API Example C# appeared first on DotNetTec.



This post first appeared on Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps API Developer, please read the originial post: here

Share the post

Google Maps Distance Matrix API Example C#

×

Subscribe to Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps Api Developer

Get updates delivered right to your inbox!

Thank you for your subscription

×