我想先写一下:我对JavaScript很新。我试图发布用户位置和映射边界与Leaflet和AJAX调用。在我的事件处理程序stateUpdater.onLocationFound
中,日志语句打印出正确的用户坐标和地图边界,但在尝试使用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);
},
};
对于可能造成这种情况的原因,我不再有任何预感,所以我非常感谢帮助。
答案 0 :(得分:5)
似乎 bounds.getNorthEast(), bounds.getSouthWest()和 e.latlng 会返回包含某些功能的对象到 lat,lng 坐标,例如等于()和 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请求被成功发送了。