How to resolve the following error: Uncaught TypeError: t.addLayer is not a function

How to resolve the following error: Uncaught TypeError: t.addLayer is not a function

我有点被这个错误困住了,希望有人能阐明这个问题。

目前我正在尝试向我的 Leaflet 地图添加一个 geoJSON 层,更具体地说是一个显示国家边界的多边形。我正在对 PHP 例程使用 AJAX 请求,该例程 returns 来自包含国家/地区数据的大型 geo.json 文件中的数据。

我卡住的地方是试图将国家 borders/polygon 添加到地图,以下错误不断打印到控制台。

控制台日志错误:

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 &copy; <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");
        }
    });

  });

您的 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 &copy; <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 变量是全局变量,您可以在点击监听器等其他函数中使用它。

我很确定,如果您在 L.geoJSON(parsedGeoJson).addTo(map); 之前添加 console.log(map),它将打印 undefined