When creating an app in PowerApps, we can use Azure Functions to add functionality that is not available in PowerApps. Additionally we can use Azure Functions to make business logic available in a PowerApps. In the PowerApps overview pages, Microsoft provides a simple example, how to add an Azure Function to a PowerApp.

This short article will show a practical example for an Azure function. In PowerApps we have access to the current location of the user. That could be helpful in a mobile app on the phone. But, PowerApps does not have function, to get the current location (the city) of the user.

With the help of the Google Maps API, we can create an Azure Function to get the current location from the longitude and the latitude. The code for our function is shown in the following listing.

#r "System.Web.Extensions"

using System.Net;
using System.Web;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");

    // parse query parameter
    string longitude = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "long", true) == 0)
        .Value;
        
    string latitude = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "lat", true) == 0)
        .Value; 
        
    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    if ((longitude != null) && (latitude != null))
    {
        string str = DoSomething(latitude, longitude);

        return req.CreateResponse(HttpStatusCode.OK, str);
    }
    else
    {
        return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a langitude and a latitude on the query string or in the request body.");
    }
}

private static string DoSomething(string latitude, string longitude)
{
    string result = String.Empty;

    var webAddress = String.Format("https://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}", latitude, longitude);
    var client = new WebClient();
    var content = client.DownloadString(webAddress);

    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

    var dict = serializer.Deserialize<Dictionary<string, dynamic>>(content);

    var status = dict["status"];

    if (status == "OK")
    {
        var results = dict["results"][0];
        var address_components = results["address_components"];
        var locality = address_components[2]["long_name"];

        result = locality;
    }
    else
    {
        // error handling
    }

    return result;
}

To make the Azure Function available in PowerApps, we need a Swagger definition file, as in the following example.

{
  "swagger": "2.0",
  "info": {
    "version": "1.0.0",
    "title": "GetLocationFromGoogleMaps"
  },
  "host": "getcityfromgeolocation.azurewebsites.net",
  "paths": {
    "/api/getlocationfromgooglemaps": {
      "get": {
        "description": "Calls my azure function over https",
        "operationId": "Run",
        "parameters": [
          {
            "name": "code",
            "in": "query",
            "description": "code",
            "default": "{enter the key from your Azure Function here}",
            "type": "string"
          },
          {
            "name": "long",
            "in": "query",
            "required": true,
            "type": "string"
          },
          {
            "name": "lat",
            "in": "query",
            "required": true,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "Successful response",
            "schema": {
              "title": "The response of the api.",
              "type": "string"
            }
          }
        }
      }
    }
  }
}

How to add this Swagger definition file to the PowerApps environment of our tenant is shown in the Microsoft example for using Azure Functions in PowerApps.

To use the function in our PowerApp, we use a very simple app. We have three fields to show the longitude, the latitude and our current location. The field for the location is a simple text field, where the Text property of the field was set to the result of the function call of our Azure Function.

The PowerApp will look like this, when we start it on a mobile phone:

In this example for the combination of PowerApps and Azure Functions I used the Google Maps API, but with a developer key we can also do the same with Bing Maps.

 

Advertisements