Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#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