I want to calculate the distance between points in C# with the google maps distance matrix API.
I use the following code to make the request :
private void MapsAPICall()
{
//Pass request to google api with orgin and destination details
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ "51.123959,3.326682" + "&destinations=" + "51.158089,4.145267"
+ "&mode=Car&language=us-en&sensor=false");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
if (!string.IsNullOrEmpty(result))
{
Distance t = JsonConvert.DeserializeObject<Distance>(result);
}
}
}
And then I want to parse the json answer into the Distance class:
public struct Distance
{
// Here I want to parse the distance and duration
}
Here is an example of the json response I receive :
http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC&destinations=San+Francisco&mode=bicycling&language=fr-FR&sensor=false
How do I parse the distance and duration into the Distance class?
This is the first time I use Json so I’m not experienced with it.
Ps: I have the json.net library installed.
Web Essentials has an option to ‘Paste JSON as classes’. This will generate the classes you need to deserialize your JSON.
Using this option will generate the following for you:
(If you want, you can refactor the generated code to make it more readable. You will need to add Json.NET attributes to make sure that serialization is still working)
Then inside your code you can use the following line to deserialize your code: