Blazor - 用户(设备)地理位置

Krz*_*zyk 6 blazor blazor-server-side

我希望可以选择在我的 blazor(服务器)应用程序上获取当前用户位置。我曾尝试使用两个解决方案 Darnton.Blazor.DeviceInterop 和 AspNetMonsters.Blazor.Geolocation。对于第一个,我遇到了如何正确使用它的问题,第二个在 NuGet 安装后破坏了整个应用程序......我将不胜感激分享其他解决方案,越简单越好

Ber*_*ton 8

如果您安装了您提到的 Blazor Geolocation 包 (Darnton.Blazor.DeviceInterop),您应该能够通过一行代码使用 GeolocationService:

CurrentPositionResult = await GeolocationService.GetCurrentPosition();
Run Code Online (Sandbox Code Playgroud)

如果你想了解里面发生的事情,我已经更详细地写了它:

https://darnton.co.nz/2020/11/29/geolocation-in-blazor/

https://darnton.co.nz/2020/11/30/geolocation-ii-position-updates/


小智 5

这花了我很长时间才弄清楚,但我想分享一个解决方案来帮助其他陷入困境的人。此解决方案适用于 Blazor 服务器应用。

首先将脚本添加到 _Layout.cshtml 文件的正文中。它看起来像这样。

<body>
@RenderBody()
<script>
window.getCoords = async () => {
    const pos = await new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject);
    });
    return [pos.coords.longitude, pos.coords.latitude];
};
<script>
</body>
Run Code Online (Sandbox Code Playgroud)

接下来,您需要将 OnAfterRenderAsync 方法添加到您的类中。此方法将调用 _Layout.cshtml 中的 JavaScript 函数

protected override async Task OnAfterRenderAsync(bool firstRender)
{
  var result = await JS.InvokeAsync<JsonArray>("getCoords");
}
Run Code Online (Sandbox Code Playgroud)

结果变量现在应该包含经度和纬度。

请注意,我期望的返回类型是 JsonArray。希望这可以帮助。


Krz*_*zyk 1

最后我将这样的脚本添加到 _Host.cshtml

<script>
    window.getCoords = async () => {            
        const pos = await new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition(resolve, reject);
        });
        document.getElementById("SearchPoint").value = pos.coords.latitude + ', ' + pos.coords.longitude

        if ("createEvent" in document) {
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent("change", false, true);
            document.getElementById("SearchPoint").dispatchEvent(evt);
        }
        else
            document.getElementById("SearchPoint").fireEvent("onchange");

    };
</script>
Run Code Online (Sandbox Code Playgroud)

以及从 blazor 组件调用该代码的代码:

private void GetLocation()
{
    JS.InvokeAsync<(long longitude, long lattitude)>("getCoords");
}
Run Code Online (Sandbox Code Playgroud)