Today I needed create some functionality to calculate the distance between zipcodes and it was not easy to me. Fortunately I found a good way and I believe it can be helpful to someone else.
Asked
Active
Viewed 1,436 times
1 Answers
3
The goal was create a delivery fee based on the distance between the store and the customer.
I did try some ways and the best is also the simplest one.
First, I needed create a viewModel based on the json response of google.
The json structure returned by the request has this format:
{
"destination_addresses" : [ "Centro, Juiz de Fora - MG, 36013-210, Brasil" ],
"origin_addresses" : [ "Passos, Juiz de Fora - MG, 36026-460, Brasil" ],
"rows" : [
{
"elements" : [
{
"distance" :
{
"text" : "3,1 km",
"value" : 3149
},
"duration" :
{
"text" : "11 minutos",
"value" : 645
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
The viewModel's properties should be the equivalent of json return properties.
In this way, my viewModel looks like this:
//Class for "distance" and "duration" which has the "text" and "value" properties.
public class CepElementNode
{
public string text { get; set; }
public string value { get; set; }
}
//Class for "distance", "duration" and "status" nodes of "elements" node
public class CepDataElement
{
public CepElementNode distance { get; set; }
public CepElementNode duration { get; set; }
public string status { get; set; }
}
//Class for "elements" node
public class CepDataRow
{
public List<CepDataElement> elements { get; set; }
}
//Class which wrap the json response
public class RequestCepViewModel
{
public List<string> destination_addresses { get; set; }
public List<string> origin_addresses { get; set; }
public List<CepDataRow> rows { get; set; }
public string status { get; set; }
}
Note that array elements as "destination_addresses", "origin_addresses" and "rows" should be a List in C#. This way we can deserialize the json response in a RequestCepViewModel instance.
Finally, in my Action I have this code:
var url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=36026460&destinations=36013210&mode=driving&language=en-EN&sensor=false";
WebRequest webRequest = WebRequest.Create(url);
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
var jsonResponseString = reader.ReadToEnd();
var viewModel = new JavaScriptSerializer().Deserialize<RequestCepViewModel>(jsonResponseString);
Hope it helps someone.
Regards

Márcio Gonzalez
- 1,020
- 1
- 8
- 20