Skip to content

Instantly share code, notes, and snippets.

@giuleon
Last active May 2, 2017 06:26
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 giuleon/64974204e1d61d5b7852e62dec79c4e5 to your computer and use it in GitHub Desktop.
Save giuleon/64974204e1d61d5b7852e62dec79c4e5 to your computer and use it in GitHub Desktop.
Azure C# Function retrieving the geolocation by latitude and longitude
#r "Newtonsoft.Json"
using System.Net;
using System.IO;
using Newtonsoft.Json;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string latlon = req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "latlon", true) == 0).Value;
log.Info("Querystring: " + latlon);
// Set name to query string or body data
dynamic data = await req.Content.ReadAsAsync<object>();
latlon = latlon ?? data?.latlon;
log.Info("Body: " + latlon);
var URI = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlon + "&key=<Insert here your Google Maps API Key>";
// call Google API
var request = System.Net.WebRequest.Create(URI) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = 0;
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
log.Info(json);
dynamic jsonData = JsonConvert.DeserializeObject(json);
return latlon == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a latitude and longitude on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, new
{
formatted_address = $"{jsonData.results[0].formatted_address}"
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment