Latest

random

Google Maps Distance Matrix Example C# ASP.Net

Google maps api distance between two lat long

The Google Distance Matrix API is a service that provides travel distance and time for a matrix of origins and destinations. The information returned is based on the recommended route between start and end points, as calculated by the Google Maps API, and consists of rows containing duration and distance values for each pair.

This article demonstrates how to get distance between two points using Google Distance Matrix API at server side using C# in asp.net. Find the code snippet below :-
google distance matrix api c#,google distance matrix api example php,google distance matrix api example java,google distance matrix javascript,distancematrixservice,driving distance matrix,distance matrix api example in android
driving distance matrix
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    /// <summary>
    /// Title: How to use Google Distance Matrix Service - JSON Format
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    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
<appSettings>
    <add key="alongroad" value="1"/>
    <add key="keyString" value="your api key"/>
    <add key="clientID" value="your client id"/>
</appSettings>

JSON Response
google distance matrix service

No comments:

All Rights Reserved by Etechpulse © 2015 - 2016
Powered By Blogger

Contact Form

Name

Email *

Message *

Powered by Blogger.