Last active
March 3, 2017 13:24
-
-
Save eugenedauphin/44ae392d6dcb5c7f66c92ba81dbd0354 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#r "Newtonsoft.Json" | |
using System; | |
using System.Net; | |
using Newtonsoft.Json; | |
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) | |
{ | |
// parse query parameter | |
string lat = req.GetQueryNameValuePairs() | |
.FirstOrDefault(q => string.Compare(q.Key, "lat", true) == 0) | |
.Value; | |
string lng = req.GetQueryNameValuePairs() | |
.FirstOrDefault(q => string.Compare(q.Key, "lng", true) == 0) | |
.Value; | |
// Get request body | |
dynamic data = await req.Content.ReadAsAsync<object>(); | |
// Set name to query string or body data | |
lat = lat ?? data?.lat; | |
lng = lng ?? data?.lng; | |
if(lat == null) | |
{ | |
return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a lat on the query string or in the request body"); | |
} | |
if(lng == null) | |
{ | |
return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a lng on the query string or in the request body"); | |
} | |
//Get route info | |
using (var client = new HttpClient()) | |
{ | |
client.DefaultRequestHeaders.Add("Accept", "application/json"); | |
var jsonResult = await client.GetStringAsync(string.Format("https://maps.googleapis.com/maps/api/directions/json?origin={0},{1}&destination=Street+Number+City&key=[Put your API key here]", lat, lng)); | |
dynamic jsonData = JsonConvert.DeserializeObject(jsonResult); | |
//Return info | |
return req.CreateResponse(HttpStatusCode.OK, new { | |
duration = $"{jsonData.routes[0].legs[0].duration.text}", | |
distance = $"{jsonData.routes[0].legs[0].distance.text}"}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment