地理位置/移动距离跟踪组件
通过浏览器API获取位置信息
演示
提示
注意:出于安全考虑,当网页请求用户位置信息时,会提示用户进行授权。请注意,不同的浏览器有不同的策略和请求权限的方式。未开启定位无法获取位置。
例子
dotnet new blazorserver -o b07geo
dotnet add b07geo package BootstrapBlazor
dotnet add b07geo package BootstrapBlazor.FontAwesome
dotnet sln add b07geo/b07geo.csproj
篇幅有限,其余步骤参考:
示例索引.razor
地理定位/移动距离追踪
单击按钮以获取地理位置坐标。
@if (WatchID == 0)
{
}
else
{
}
@if (Model != null)
{
}
@Trace
cs文件,如Index.razor.cs
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using Microsoft.JSInterop;
namespace b07geo.Pages;
public partial class Index : IAsyncDisposable
{
private JSInterop? Interop { get; set; }
private string Trace;
[Inject]
private IJSRuntime? JSRuntime { get; set; }
private GeolocationItem? Model { get; set; }
///
/// 获得/设置 获取持续定位监听器ID
///
private long WatchID { get; set; }
private async Task GetLocation()
{
Interop ??= new JSInterop(JSRuntime);
var ret = await Geolocation.GetLocaltion(Interop, this, nameof(GetLocationCallback));
Trace += (ret ? "成功获取定位" : "获取定位失败");
}
private async Task WatchPosition()
{
try
{
Interop ??= new JSInterop(JSRuntime);
WatchID = await Geolocation.WatchPosition(Interop, this, nameof(GetLocationCallback));
Trace += WatchID != 0 ? "调用 WatchPosition 成功" : "调用 WatchPosition 失败";
Trace += $"WatchID : {WatchID}";
}
catch (Exception)
{
Trace += "调用 WatchPosition 失败";
}
}
private async Task ClearWatchPosition()
{
if (WatchID != 0)
{
Interop ??= new JSInterop(JSRuntime);
var ret = await Geolocation.ClearWatchPosition(Interop, WatchID);
if (ret)
{
WatchID = 0;
}
Trace += ret ? "停止追踪成功" : "停止追踪失败";
}
}
///
///
///
///
[JSInvokable]
public void GetLocationCallback(GeolocationItem item)
{
Model = item;
StateHasChanged();
}
///
///
///
///
protected virtual async ValueTask DisposeAsync(bool disposing)
{
if (disposing)
{
if (Interop != null)
{
if (WatchID != 0)
{
await Geolocation.ClearWatchPosition(Interop, WatchID);
}
Interop.Dispose();
Interop = null;
}
}
}
///
///
///
public async ValueTask DisposeAsync()
{
await DisposeAsync(true);
GC.SuppressFinalize(this);
}
}
模拟跟踪定位
/edge F12进入调试模式后,点击右上角三点图标,选择更多工具、传感器、定位
选择一个地理位置,开启组件定位跟踪后,可以慢慢调整参数测试组件功能。 :->
组件库文档
写在最后
希望大佬们看到这篇文章,给项目一个star支持下,谢谢!
星级流程:
1、访问并点击项目链接:
2、@ >点击star,如下图即可完成star,关注项目不迷路:
还有另外两个 GVP 项目。
项目地址:
项目地址:
交流群(QQ)欢迎加群讨论
BA & ①() BA & ②()
© 版权声明
本站下载的源码均来自公开网络收集转发二次开发而来,
若侵犯了您的合法权益,请来信通知我们1413333033@qq.com,
我们会及时删除,给您带来的不便,我们深表歉意。
下载用户仅供学习交流,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担,访问及下载者下载默认同意本站声明的免责申明,请合理使用切勿商用。
THE END
暂无评论内容