Some of my side project apps base themselves on showing the user the distance between them and some given locations. In Xamarin.Forms this is easily done with Xamarin.Essentials, but in .NET MAUI it’s even easier. The .NET MAUI essentials are built into the framework itself and doesn’t rely on an external package. Here I’ll show you just how easily its done using Android.
Using the latest preview version of Visual Studio (17.1 Preview 3), create a new .NET MAUI project. Lets modify the boilerplate MainPage.xaml.cs
-file that was generated and remove everything inside the OnCounterClicked
-method. What we need first is the user’s location. We’ll get this by using the Geolocation
from the Microsoft.Maui.Essentials
namespace:
var myLocation = await Geolocation.GetLocationAsync();
If we want this to run on Android, we’ll have to set the proper permissions for retrieving locations first. Locate the AndroidManifest.xml file (in .NET MAUI, this is located under Platforms -> Android):
Add the following lines to the file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Currently there seems to be a bug with .NET MAUI essentials, which gives you an error if you try to run this. This GitHub answer seems to be a work-around until they fix the issue.
Next we’ll define a location we want to calculate the distance to. Here I’m creating a location which has the coordinates for a grocery store nearby:
var otherLocation = new Location(58.9438705, 5.7118685);
Now for the main event: calculating the distance between the two. .NET MAUI essentials provides a nifty extension method you can use on any Location
-object. This takes the input of the location to calculate the distance to and what type of distance unit you want it to return (miles or kilometers):
var distance = myLocation.CalculateDistance(otherLocation, DistanceUnits.Kilometers);
This returns a double
, which we might want to round. Finally we can use the existing CounterLabel
to display the distance on the label, rounding it to show only two decimal digits:
CounterLabel.Text = $"Distance to Brustadbua: {distance:0.##} km";
And that’s it! 4 lines of code (technically 3) is all you need. Note that this most likely gives you the distance “as the crow flies”.
I’ve provided a sample for this on GitHub if you want to clone it and check it out. Hope you found this useful!
Well done
You simply help solve my problem.
Although i tested it on desktop it worked very well just thati notice that when i change location, (I move my computer to another building within same vicinity, my lacation result still showed same longtitde and latitude. is it because of desktop or i nee to do something
thanks i appreciate