In this blog post, you will learn the google maps distance matrix api example in C#. It will demonstrate to you how to calculate the distance between two points using the Google Matrix API which is a service that provides travel distance and journey duration for a matrix of origins and destinations using a given mode of travel.
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#
To use a Google Maps API you must obtain an API key. The APIs are also subject to API policies and usage quotas, which may differ per API. The API keys and quotas will be explained later in this document in more detail. 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.
Find the below source code:-
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 <configuration> <system.web> <compilation debug="true" targetFramework="4.0"/> </system.web> <appSettings> <add key="alongroad" value="1"/> <add key="keyString" value="your api key"/> <add key="clientID" value="your client id"/> </appSettings> </configuration>
References:
Conclusion
I hope you liked this article on the google maps distance matrix api example. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Leave a Reply