Google Distance Matrix Api With Httpclient And Json Net
Google Map is excellent. So is Google Map API. This article will create a simple class with HttpClient and Json.NET to utilise Google Distance Matrix API.
Add System.Net.Http reference for HttpClient and install Newtonsoft.Json Nuget Package
Add API Url and API Key settings into Web.config
GoogleDistanceMatrixApi Constructor
The constructor receives origin addresses and destination addresses from the user and it gets App Url and Key settings from AppSettings. If the Url and Key settings are missing, it will throw an exception.
Generate request url
All addresses need to be url encoded.
Response Ojbect
This Response class maps API response. Json.NET can parse Json into a C# class. It is handy for us to analyse the result later on. We use JsonProperty attribute here to map Json properties to class properties if they are different.
Request with HttpClient
HttpClient’s built in async feature makes program efficient. JsonConvert parses Json response into a Response class we defined.