我有点被这个错误困住了,我希望有人能对这个问题有所了解。
目前,我正试图在我的传单地图中添加一个geoJSON层,更具体地说,是一个显示国家边界的多多边形。我对一个PHP例程使用AJAX请求,该例程从包含国家数据的大型geo.json文件中返回数据。
我被困的地方是试图将国家边框/多边形添加到地图中,下面的错误一直打印到控制台上。
控制台日志错误:
Layer.js:52 Uncaught TypeError: t.addLayer is not a function
at i.addTo (Layer.js:52)
at Object.success (index.js:104)
at fire (jquery-3.6.0.js:3500)
at Object.fireWith [as resolveWith] (jquery-3.6.0.js:3630)
at done (jquery-3.6.0.js:9796)
at XMLHttpRequest.<anonymous> (jquery-3.6.0.js:10057)我怀疑我在ajax成功函数中做错了什么,因为我试图将数据添加到地图中,但是,经过几天的尝试,我现在需要专家的建议。
此外,我还检查了我的文件是否正确链接。
任何建议都将不胜感激,谢谢!
我的一些代码:
//传单地图初始化
var map = L.map('map').setView([51.509, -0.08], 15);
L.tileLayer('https://tile.thunderforest.com/atlas/{z}/{x}/{y}.png?apikey={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="http://www.thunderforest.com/">Thunderforest</a>',
maxZoom: 18,
id: 'thunderforest/atlas',
accessToken: 'a794617134d14b1f82f1cd09d35bca51'
}).addTo(map);
var polygon = L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(map);
var marker = new L.Marker([51.509, -0.08]);
marker.addTo(map);
});//国家边界AJAX请求
$('#borderSearch').click(function(){
$.ajax({
url: "lib/php/border.php",
type: "POST",
dataType: 'json',
data: {
code: $('#countryName').val()
},
success: function(result) {
var borderData = JSON.stringify(result);
var parsedGeoJson = JSON.parse(borderData);
L.geoJSON(parsedGeoJson).addTo(map);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("Request Failed");
}
});
});发布于 2021-12-25 07:07:11
您的map变量是在另一个函数中初始化的,无法访问全局。
var map;
$.ready(function(){ // Your function, I don't know what you do here, but I that you call this code in a function. Maybe `.ready(` or something like this
map = L.map('map').setView([51.509, -0.08], 15);
L.tileLayer('https://tile.thunderforest.com/atlas/{z}/{x}/{y}.png?apikey={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="http://www.thunderforest.com/">Thunderforest</a>',
maxZoom: 18,
id: 'thunderforest/atlas',
accessToken: 'a794617134d14b1f82f1cd09d35bca51'
}).addTo(map);
var polygon = L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(map);
var marker = new L.Marker([51.509, -0.08]);
marker.addTo(map);
});并知道map变量是全局变量,您可以在其他函数中使用它,比如单击侦听器。
我非常肯定,如果在console.log(map)之前添加L.geoJSON(parsedGeoJson).addTo(map);,它将打印undefined
https://stackoverflow.com/questions/70472275
复制相似问题