gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'lat' of undefined when serializing leaflet data with $. 参数()

转载 作者:数据小太阳 更新时间:2023-10-29 05:23:00 25 4
gpt4 key购买 nike

我想先说明一下:我是 JavaScript 的新手。我正在尝试使用 Leaflet 和 AJAX 调用发布用户位置和 map 边界。在我的事件处理程序 stateUpdater.onLocationFound 中,日志语句打印出正确的用户坐标和 map 边界,但是我在尝试时得到 Uncaught TypeError: Cannot read property 'lat' of undefined使用 $.param() 序列化这些值。我正在使用 Leaflet v0.7.2 和 jQuery 1.11.0。

var map;

$(document).ready(function() {
map = new L.map('map').setView([41.52, -71.09], 11);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
map.on('locationfound', stateUpdater.onLocationFound);

stateUpdater.poll();
});

var stateUpdater = {
errorSleepTime: 10000,

poll: function() {
map.locate({setView: true, maxZoom: 18});
},

onLocationFound: function(e) {
//This log statement produces the correct output
console.log(e.latlng.toString());
var bounds = map.getBounds();
//As does this one
console.log(bounds.toBBoxString())
var args = {
"map_ne": bounds.getNorthEast(),
"map_sw": bounds.getSouthWest(),
"user_coords": e.latLng
};
//Uncaught TypeError thrown here
$.ajax({url: "/a/state/updates", type: "POST", dataType: "text",
data: $.param(args),
success: stateUpdater.onSuccess,
error: stateUpdater.onError});
},

onSuccess: function(response) {
console.log(response);
stateUpdater.errorSleepTime = 10000;
window.setTimeout(stateUpdater.poll, 10000);
},

onError: function(response) {
stateUpdater.errorSleepTime *= 2;
console.log("Poll error; sleeping for", stateUpdater.errorSleepTime, "ms");
window.setTimeout(stateUpdater.poll, stateUpdater.errorSleepTime);
},
};

对于可能导致此问题的原因,我没有任何预感,因此非常感谢您的帮助。

最佳答案

似乎 bounds.getNorthEast()bounds.getSouthWest()e.latlng 返回的对象还包含一些函数到 lat,lng 坐标,比如 equal()toString() 防止 $.param()正确执行数据序列化并导致错误,这是从这些对象中仅获取所需内容的好方法:

    var ll= $.extend({},{lat:e.latlng.lat, lng:e.latlng.lng}), 
neBounds = bounds.getNorthEast(),
neBoundsLl = $.extend({},{lat:neBounds.lat, lng:neBounds.lng}),
swBounds = bounds.getSouthWest(),
swBoundsLl = $.extend({},{lat:swBounds.lat, lng:swBounds.lng}),
args = {
"map_ne": neBoundsLl,
"map_sw": swBoundsLl,
"user_coords": ll
};

我测试了这段代码,它对我有用,错误消失了,ajax 请求发送成功。

关于javascript - 未捕获的类型错误 : Cannot read property 'lat' of undefined when serializing leaflet data with $. 参数(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22317655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com