Use this Class in your project to get driving distance between two places
You can get Newtonsoft.Json.Linq namespace from https://json.codeplex.com/releases/view/117958
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Management
{
class DeliveryMapInfo
{
string origin = @""; //Write the address of the origin here
public DeliveryMapInfo() { }
public int getDistanceTo(string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = -1;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;string content = fileGetJSON(requesturl);
JObject _Jobj = JObject.Parse(content);
try
{
distance = (int)_Jobj.SelectToken("routes[0].legs[0].distance.value");
return distance / 1000;// Distance in KMS
}
catch
{
return distance / 1000;
}
}
protected string fileGetJSON(string fileName)
{
string _sData = 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);
_sData = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
_sData = sr.ReadToEnd();
sr.Close();
}
}
catch { _sData = "unable to connect to server "; }
return _sData;
}
}
}
A lot of your idea depends upon what api you want to use, ie. Distance Matrix, Directions, Geocoding, etc.
Notice: "/directions/"
I found directions as most complete api for my use, since it can geocode, find distance, find durations... etc.
However the size of directions json file is larger than other json files.
Use your judgement.
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
and
distance = (int)_Jobj.SelectToken("routes[0].legs[0].distance.value");
for eg:
The Structure inside Directions json file is:
-Routes
- Bound
- NorthEast
- SouthWest
- Copyrights
- Legs
- Steps
- duration
- distance
- endlocation
- maneuver
- htmlinstructions
- polyline
- startlocation
- travelmode
- Distance
- text
- value
- Duration
- test
- value
- StartAddress
- EndAddress
- EndLocation
- lat
- lng
- StartLocation
- lat
- lng
- Overview Polyline
- Summary
- Warnings
- Waypoint Order
- Status