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

jQuery调用Google Map用变量传经纬度报InvalidValueError如何解决

错误原因

  • 接口返回的UserLatitude、UserLongitude是字符串格式,Google Maps API要求坐标值必须为数字类型,即使是内容为数字的字符串也无法被识别。
  • 若遍历结果中没有匹配到ClusterId = '2414040001'的项,两个全局变量会被赋值为空字符串,或者根本未被赋值,也会触发类型校验错误。

解决方法

赋值时将坐标转换为数字类型,同时补充兜底的默认坐标,避免无匹配项时报错:

success: function(result) {
    // 先设置测试可用的兜底坐标,避免接口无匹配数据时报错
    let UserLatitude = -33.890
    let UserLongitude = 151.274

    for (var i = 0; i < result['Result'].length; i++) {
        if (result['Result'][i]['ClusterId'] == '2414040001') {
            if (result['Result'][i]['UserLatitude'] != '' &&
                result['Result'][i]['UserLatitude'] != null) {
                // 把返回值转换为数字类型
                UserLatitude = Number(result['Result'][i]['UserLatitude'])
            }
            if (result['Result'][i]['UserLongitude'] != '' &&
                result['Result'][i]['UserLongitude'] != null) {
                // 把返回值转换为数字类型
                UserLongitude = Number(result['Result'][i]['UserLongitude'])
            }
            console.log("LAT:" + UserLatitude + "LONG:" + UserLongitude);
        }
    }

    const myLatLng = {
        lat: UserLatitude,
        lng: UserLongitude
    };
    console.log(myLatLng);
    const map = new google.maps.Map(document.getElementById("googleMap"), {
        zoom: 4,
        center: myLatLng,
    });

    new google.maps.Marker({
        position: myLatLng,
        map,
        title: "Hello World!",
    });
}

修改说明:

  • 提前初始化坐标变量为测试正常的兜底值,避免接口无匹配数据时报错
  • 拿到接口返回的坐标后用Number()方法转换为数字类型,符合Google Maps API的参数要求
  • 不需要挂载到window全局对象,局部变量就能满足当前作用域的使用需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:18:01