Leaflet js:未捕获的类型错误:无法读取未定义的属性“addLayer”

Ils*_*lse 2 javascript leaflet

我正在尝试使用 Leaflet 创建地图并在地图上显示标记。有没有人对我在地图上显示标记时收到的以下错误有任何想法?

我可以启动页面的地图加载:

var map;
var ajaxRequest;
var plotlist;
var plotlayers=[];

function initmap() {
    // set up the map
    map = new L.Map('map');

    // create the tile layer with correct attribution
    var osmUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmAttrib='Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
    var osm = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 20, attribution: osmAttrib});       

    // start the map over Holland
    map.setView(new L.LatLng(52.36994, 4.90788),8);
    map.addLayer(osm);
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个标记:

var marker=L.marker([52.63275, 4.75175]).bindPopup('testmarker');
Run Code Online (Sandbox Code Playgroud)

将标记添加到地图时,出现错误“Uncaught TypeError: Cannot read property 'addLayer' of undefined”:

marker.addTo(map);
Run Code Online (Sandbox Code Playgroud)

当在 initmap() 函数中包含这一行时,它工作正常。所以看起来地图实例是不可访问的还是函数之外的东西?哪个很奇怪,因为变量是在脚本开始时在函数之外创建的?

谢谢!

Ils*_*lse 8

解决了。map 实例是在 dom 完全加载之前创建的,所以 div 'map' 还不存在。我将包含 javascript 的脚本标签从页​​面的头部移动到正文的末尾。