变量在Jquery为谷歌地图



我有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!",
});


}

我从远程服务器获得纬度和经度,并希望将其用于谷歌地图。如果我在

下面使用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

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

谢谢!

服务器返回的响应可能是字符串。你能试一下这个代码解析的lat和长值浮动lat和lng值使用parseFloat()方法从javascript。

// 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!",
});

最新更新