Skip to content

Instantly share code, notes, and snippets.

@eugenedauphin
Last active March 3, 2017 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eugenedauphin/44ae392d6dcb5c7f66c92ba81dbd0354 to your computer and use it in GitHub Desktop.
Save eugenedauphin/44ae392d6dcb5c7f66c92ba81dbd0354 to your computer and use it in GitHub Desktop.
#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