You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Blazor中不依赖库实现简易地理位置(经纬度)获取?

在Blazor中无第三方依赖获取经纬度的最简方案

如果你想在Blazor里获取用户经纬度,又不想引入第三方库,可以试试这个仅用少量JavaScript实现的方案:

实现思路

核心逻辑是让Blazor组件向JavaScript传递一个回调函数,调用浏览器原生地理定位API获取经纬度后,通过该回调把结果传回组件;同时在等待结果的过程中显示加载动画,提升用户体验。

代码实现

Blazor 组件代码

@inject IJSRuntime JSRuntime

<button @onclick="GetLocation">获取当前位置</button>

@if (isLoading)
{
    <p>正在获取位置...</p>
}

@if (locationResult != null)
{
    <p>纬度: @locationResult.Latitude, 经度: @locationResult.Longitude</p>
}

@code {
    private bool isLoading;
    private LocationData locationResult;

    private async Task GetLocation()
    {
        isLoading = true;
        StateHasChanged();

        await JSRuntime.InvokeVoidAsync("getUserLocation", DotNetObjectReference.Create(this));
    }

    [JSInvokable]
    public void ReceiveLocation(double latitude, double longitude)
    {
        locationResult = new LocationData { Latitude = latitude, Longitude = longitude };
        isLoading = false;
        StateHasChanged();
    }

    public class LocationData
    {
        public double Latitude { get; set; }
        public double Longitude { get; set; }
    }
}

JavaScript 代码

直接放在wwwroot下的script.js或页面的<script>标签中:

function getUserLocation(componentReference) {
    if (!navigator.geolocation) {
        alert("浏览器不支持地理定位");
        componentReference.invokeMethodAsync('ReceiveLocation', 0, 0);
        return;
    }

    navigator.geolocation.getCurrentPosition(
        (position) => {
            componentReference.invokeMethodAsync(
                'ReceiveLocation',
                position.coords.latitude,
                position.coords.longitude
            );
        },
        (error) => {
            alert(`获取位置失败: ${error.message}`);
            componentReference.invokeMethodAsync('ReceiveLocation', 0, 0);
        }
    );
}

操作说明

  1. 点击按钮触发GetLocation方法,设置加载状态并调用JavaScript函数
  2. JavaScript调用浏览器原生API获取经纬度,成功或失败都会通过回调通知Blazor组件
  3. 组件收到结果后更新状态,隐藏加载动画并展示经纬度信息

内容的提问来源于stack exchange,提问作者user1489673

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:05:33