using Microsoft.JSInterop; using System; using System.Threading.Tasks; namespace Darnton.Blazor.DeviceInterop.Geolocation { /// /// An implementation of that provides /// an interop layer for the device's Geolocation API. /// public class GeolocationService : IGeolocationService { private readonly IJSRuntime _jsRuntime; /// public event EventHandler WatchPositionReceived; /// /// Constructs a object. /// /// public GeolocationService(IJSRuntime JSRuntime) { _jsRuntime = JSRuntime; } /// public async Task GetCurrentPosition(PositionOptions options = null) { return await _jsRuntime.InvokeAsync("Geolocation.getCurrentPosition", options); } /// public async Task WatchPosition(PositionOptions options = null) { var callbackObj = DotNetObjectReference.Create(this); return await _jsRuntime.InvokeAsync("Geolocation.watchPosition", callbackObj, nameof(SetWatchPosition), options); } /// /// Invokes the event handler. /// Invoked by the success and error callbacks of the JavaScript watchPosition() function. /// /// A passed back from JavaScript. [JSInvokable] public void SetWatchPosition(GeolocationResult watchResult) { WatchPositionReceived?.Invoke(this, new GeolocationEventArgs { GeolocationResult = watchResult }); } /// public async Task ClearWatch(long watchId) { await _jsRuntime.InvokeVoidAsync("Geolocation.clearWatch", watchId); } } }