Hello,
You could try to query the current device's location coordinates by Xamarin.Essentials: Geolocation, then call the OpenAsync
method with this Location
by Xamarin.Essentials: Map. Refer to the following code:
CancellationTokenSource cts;
protected async override void OnAppearing()
{
base.OnAppearing();
try
{
var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
cts = new CancellationTokenSource();
var location = await Geolocation.GetLocationAsync(request, cts.Token);//get the location
if (location != null)
{
Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
var options = new MapLaunchOptions { Name = "Microsoft Building 25" };
await Map.OpenAsync(location, options);//open Map
}
}
catch (FeatureNotSupportedException fnsEx)
{
// Handle not supported on device exception
Console.WriteLine("{0}", fnsEx);
}
catch (FeatureNotEnabledException fneEx)
{
Console.WriteLine("{0}", fneEx);
// Handle not enabled on device exception
}
catch (PermissionException pEx)
{
// Handle permission exception
Console.WriteLine("{0}", pEx);
}
catch (Exception ex)
{
// Unable to get location
Console.WriteLine("{0}", ex);
}
}
protected override void OnDisappearing()
{
if (cts != null && !cts.IsCancellationRequested)
cts.Cancel();
base.OnDisappearing();
}
Before using Geolocation, you need to set the Location permissions on iOS and Android platform, refer to https://learn.microsoft.com/en-us/xamarin/essentials/geolocation?tabs=android#get-started and https://learn.microsoft.com/en-us/xamarin/essentials/geolocation?tabs=ios#get-started
Best Regards,
Wenyan Zhang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.