【问题标题】:Leaflet js: Uncaught TypeError: Cannot read property 'addLayer' of undefinedLeaflet js:未捕获的类型错误:无法读取未定义的属性“addLayer”
【发布时间】:2018-10-30 17:14:35
【问题描述】:

我正在尝试使用 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);
}

我创建了一个标记:

var marker=L.marker([52.63275, 4.75175]).bindPopup('testmarker');

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

marker.addTo(map);

在 initmap() 函数中包含这一行时,它可以正常工作。如此看来,地图实例无法访问或功能之外的东西?这很奇怪,因为变量是在脚本开始时在函数之外创建的?

谢谢!

【问题讨论】:

    标签: javascript leaflet


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 2018-07-30
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多