Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 = "" + 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();
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