【问题标题】:variable in Jquery For Google MapJquery For Google Map 中的变量
【发布时间】:2021-09-16 15:29:04
【问题描述】:

我有如下 ajax 成功函数

success: function(result) {

    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) {
                window.UserLatitude = result['Result'][i][
                    'UserLatitude'
                ];
            } else {
                window.UserLatitude = '';
            }

            if (result['Result'][i]['UserLongitude'] != '' &&
                result['Result'][i]['UserLongitude'] != null) {
                window.UserLongitude = result['Result'][i][
                    'UserLongitude'
                ];
            } else {
                window.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: {
            lat: -33.890,
            lng: 151.274
        },
        map,
        title: "Hello World!",
    });




}

我正在从远程服务器获取纬度和经度,并希望将其用于 Google 地图。 如果我像下面这样使用 const ,它工作正常

const myLatLng = { lat: -33.890, lng: 151.274 };

但如果我为它使用变量,它会给我如下错误

InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: not a number

我不知道是什么问题以及如何解决它。

谢谢!

【问题讨论】:

  • 请不要设置任何东西window
  • 对变量使用 parseFloat。
  • @naxsi,parseFloat 已经解决了这个问题。谢谢!

标签: javascript jquery


【解决方案1】:

服务器返回的响应可能是字符串。您能否尝试此代码使用 javascript 中的 parseFloat() 方法将 lat 和 long 值解析为浮动 lat 和 lng 值。

// const myLatLng = { lat: UserLatitude, lng: UserLongitude };
// change above code to 
const myLatLng = { lat: parseFloat(UserLatitude), lng: parseFloat(UserLongitude) };
                  console.log(myLatLng);
                  const map = new google.maps.Map(document.getElementById("googleMap"), {
                    zoom: 4,
                    center: myLatLng,
                  });
                
                  new google.maps.Marker({
                    position: {lat: -33.890, lng: 151.274},
                    map,
                    title: "Hello World!",
                  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多