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

Blazor中Google Maps添加多标记报错:经纬度无效问题排查

问题:Blazor中Google Maps添加标记时提示“Invalid latitude or longitude”

在Blazor项目中给Google Maps添加多个标记,通过DisplayRespondersOnMap方法从Firestore数据库获取响应者坐标,转换为数组后传给JavaScript函数addMarkersToMap。但调用时控制台持续提示“Invalid latitude or longitude”,地图呈灰色但可交互。日志显示C#和JS端的坐标值均正确,但经纬度被判定为无效。

C#代码

private async Task DisplayRespondersOnMap()
{
    List<string> respondersList = update.Responder.ToList();

    foreach (string responder in respondersList)
    {
        Console.WriteLine($"Responder: {responder}");
    }

    List<(double latitude, double longitude)> coordinates = await FirestoreService.GetRespondersCoordinates(respondersList);

    foreach (var coord in coordinates)
    {
        Console.WriteLine($"Latitude: {coord.latitude}, Longitude: {coord.longitude}");
    }

    var coordinatesArray = coordinates.Select(coord => new double[] { coord.latitude, coord.longitude }).ToArray();

    Console.WriteLine("Coordinates Array:");
    foreach (var coordArray in coordinatesArray)
    {
        Console.WriteLine($"[{coordArray[0]}, {coordArray[1]}]");
    }

    Console.WriteLine("Calling JavaScript function addMarkersToMap...");
    await JSRuntime.InvokeVoidAsync("addMarkersToMap", coordinatesArray);

    Console.WriteLine("JavaScript function addMarkersToMap called.");
}

JavaScript代码

function addMarkersToMap(locations) {
    try {
        console.log('Adding markers to map...');

        if (!Array.isArray(locations)) {
            throw new Error('Invalid locations array.');
        }

        console.log('Locations array:', locations);

        var trackingMap = new google.maps.Map(document.getElementById('tracking-map'), {
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.TERRAIN
        });

        locations.forEach(location => {
            var latitude = parseFloat(location[0]);
            var longitude = parseFloat(location[1]);

            if (isNaN(latitude) || isNaN(longitude)) {
                console.error('Invalid latitude or longitude:', location);
                return;
            }

            var latLng = new google.maps.LatLng(latitude, longitude);

            var marker = new google.maps.Marker({
                position: latLng,
                map: trackingMap,
                title: 'Your Marker Title'
            });

            console.log('Marker added at Latitude:', latitude, ' Longitude:', longitude);
        });

        console.log('All markers added successfully.');
    } catch (error) {
        console.error('Error adding markers to map:', error);
    }
}

控制台日志

  • C#端坐标数组输出:
    Coordinates Array:
    [14.4129238, 120.9815481]
    
  • JS端接收的locations数组:
    Locations array: Array(2)
    0: 14.4129238
    1: 120.9815481
    length: 2
    
  • 错误提示:
    Invalid latitude or longitude: 14.4129238
    Invalid latitude or longitude: 120.9815481
    

解决方案

核心问题

C#传递的是二维数组(每个标记对应一个包含经纬度的子数组),但JavaScript代码错误地将外层数组的每个元素当作单个坐标值处理。比如当C#传[[14.4129238, 120.9815481]]时,JS遍历到的location是14.4129238,取location[0]会得到undefined,转换为浮点数后就是NaN,触发无效经纬度的错误。

修正后的JavaScript代码

function addMarkersToMap(locations) {
    try {
        console.log('Adding markers to map...');

        if (!Array.isArray(locations)) {
            throw new Error('Invalid locations array.');
        }

        console.log('Locations array:', locations);

        var trackingMap = new google.maps.Map(document.getElementById('tracking-map'), {
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.TERRAIN
        });

        // 如果有坐标,设置地图中心到第一个标记位置(可选)
        if (locations.length > 0 && Array.isArray(locations[0]) && locations[0].length === 2) {
            const firstLatLng = new google.maps.LatLng(locations[0][0], locations[0][1]);
            trackingMap.setCenter(firstLatLng);
        }

        // 遍历每个包含经纬度的子数组
        locations.forEach(coordPair => {
            // 先验证当前项是否为合法的坐标数组
            if (!Array.isArray(coordPair) || coordPair.length !== 2) {
                console.error('Invalid coordinate format:', coordPair);
                return;
            }

            const latitude = parseFloat(coordPair[0]);
            const longitude = parseFloat(coordPair[1]);

            // 验证经纬度是否为有效数字,且在合法范围内
            if (isNaN(latitude) || isNaN(longitude)) {
                console.error('Invalid latitude or longitude:', coordPair);
                return;
            }
            if (latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180) {
                console.error('Latitude or longitude out of valid range:', coordPair);
                return;
            }

            const latLng = new google.maps.LatLng(latitude, longitude);

            new google.maps.Marker({
                position: latLng,
                map: trackingMap,
                title: 'Responder Location'
            });

            console.log('Marker added at Latitude:', latitude, ' Longitude:', longitude);
        });

        console.log('All markers added successfully.');
    } catch (error) {
        console.error('Error adding markers to map:', error);
    }
}

额外验证(可选)

确认C#端传递的coordinatesArray是二维数组结构:

  • 当有1个响应者时,结构应为new double[][] { new double[] {14.4129238, 120.9815481} }
  • 当有多个响应者时,结构应为new double[][] { new double[] {lat1, lng1}, new double[] {lat2, lng2} }

内容的提问来源于stack exchange,提问作者Joey Martinez Jr.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:35:58