PowerApps: Fetching Longitude and Latitude to Determine Closest Locations
Discovering the closest location and sorting records by proximity based on the user’s current position is a crucial feature for many apps. Especially when you have a dataset full of locations, and you’re trying to find which one is nearest to a user. This article delves into the formula to accomplish this in PowerApps.
Understanding the Problem
Imagine having a list of locations. How do we identify the record closest to the user’s current position? Furthermore, how can we organize the records based on their relative distance to the user? We’ll uncover this as we progress.
Practical Demonstration
To illustrate, consider a map of the following underground stations along with their latitude and longitude:
- Bayswater: 51.512254, -0.187522
- Queensway: 51.510473, -0.186959
- Lancaster Gate: 51.511721, -0.175290
If we’re situated at the coordinates 51.512611, -0.182105, how do we determine the nearest underground station and list them based on their relative distances?
Configuring Our Dataset
For demonstration purposes, we’ll utilize the below collection as our dataset. In real-world scenarios, this could be sourced from SharePoint lists or other platforms:
ClearCollect(undergroundLocations, {StationName:"Bayswater", LatValue:51.512254, LongValue:-0.187522}, {StationName:"Queensway", LatValue:51.510473, LongValue:-0.186959}, {StationName:"Lancaster Gate", LatValue:51.511721, LongValue:-0.175290} )
Formula for Calculating and Sorting by Distance
We employ the renowned Haversine formula to determine distance. The formula calculates the distance between two coordinates based on their longitude and latitude. Using the PowerApps platform, we add a column named “Distance” to our dataset and apply this formula:
SortByColumns( AddColumns( undergroundLocations, "Distance", With( { earthRadius: 6371, radianFactor: (Pi() / 180), inputLat: 51.512611, inputLon: -0.182105, dataLat: LatValue, dataLon: LongValue }, (2 * earthRadius) * Asin(Sqrt(0.5 - Cos((inputLat - dataLat) * radianFactor)/2 + Cos(dataLat * radianFactor) * Cos(inputLat * radianFactor) * (1 - Cos((inputLon - dataLon) * radianFactor)) / 2)) ) ), "Distance", Ascending )
Here, inputLat
and inputLon
pertain to our chosen coordinate. You can adjust these values or replace them with Location.Latitude
and Location.Longitude
to capture the user’s real-time location in PowerApps.
Testing the Formula
Upon applying the above formula in PowerApps, the result revealed Bayswater as the nearest underground station at a distance of 0.3km.
Conclusion
In PowerApps, using the Haversine formula, we efficiently sorted a list of locations based on their relative distance to a chosen coordinate. This capability is vital for apps aiming to provide location-based services or features to users. For further assistance on this topic or any other technical queries, feel free to contact us. We are here to help and provide solutions tailored to your needs.