Geolocation
How to use the Geolocation class of the bit Butil?
Usage
To read the device's position you need to inject the Bit.Butil.Geolocation class and use it like this:
@inject Bit.Butil.Geolocation geolocation
@code {
var position = await geolocation.GetCurrentPosition();
await using var sub = await geolocation.SubscribeWatch(p => { /* ... */ });
}Methods
The Geolocation class wraps the
Geolocation API
(navigator.geolocation).
IsSupported:
Returns whether the Geolocation API (navigator.geolocation) is available in the current browser (MDN).
GetCurrentPosition:
Returns the device's current position once. The browser prompts for permission on first use (MDN).
SubscribeWatch:
Subscribes to continuous position updates and returns a ButilSubscription handle. Dispose the handle to stop watching (MDN).
IsSupported:
Returns whether the Geolocation API (navigator.geolocation) is available in the current browser (MDN).
@inject Bit.Butil.Geolocation geolocation
<BitButton OnClick="IsSupported">IsSupported</BitButton>
<div>Is supported: @isSupported</div>
@code {
private string? isSupported;
private async Task IsSupported()
{
isSupported = (await geolocation.IsSupported()).ToString();
}
}GetCurrentPosition:
Returns the device's current position once. The browser prompts for permission on first use (MDN).
@inject Bit.Butil.Geolocation geolocation
<BitButton OnClick="GetCurrentPosition">GetCurrentPosition</BitButton>
<div>Current position: @currentPosition</div>
@code {
private string? currentPosition;
private async Task GetCurrentPosition()
{
try
{
var position = await geolocation.GetCurrentPosition();
var coords = position.Coords;
currentPosition = $"lat={coords.Latitude:F6}, lng={coords.Longitude:F6}, accuracy={coords.Accuracy:F1}m";
}
catch (GeolocationException ex)
{
currentPosition = $"{ex.Code} → {ex.Message}";
}
}
}SubscribeWatch:
Subscribes to continuous position updates and returns a ButilSubscription handle. Dispose the handle to stop watching (MDN).
@inject Bit.Butil.Geolocation geolocation
<BitButton OnClick="StartWatch">Start watch</BitButton>
<BitButton OnClick="StopWatch">Stop watch</BitButton>
<div>Watch: @watchResult</div>
@code {
private ButilSubscription? watchSub;
private async Task StartWatch()
{
await StopWatch();
watchSub = await geolocation.SubscribeWatch(
onPosition: position =>
{
var coords = position.Coords;
watchResult = $"lat={coords.Latitude:F6}, lng={coords.Longitude:F6}";
InvokeAsync(StateHasChanged);
});
}
private async Task StopWatch()
{
if (watchSub is null) return;
await watchSub.DisposeAsync();
watchSub = null;
}
}