mapbox gl js - Uncaught TypeError:无法读取属性' classList'为null

时间:2016-05-24 19:21:30

标签: javascript html node.js mapbox mapbox-gl-js

我正在用MapBox GL JS创建一个地图。我在index.html页面上创建了一个地图并且工作正常,但现在我正在尝试在单独的页面上创建另一个地图,并且当引用地图应该去的div时,我收到错误:

  

未捕获的TypeError:无法读取属性' classList' null。

我不确定为什么会发生这种情况,因为我在我的html中创建了元素,而我的javascript与在index.html页面上成功创建第一个地图的javascript相同(但在不同的div上)。我在Node.js中这样做,并将webpack捆绑到main.min.js文件中,我在index.html和第二个html页面上引用它。



"use strict"
//here is the MapBox GL JS code at the point the error references in the console
 //_setupContainer: function() {
   //     var container = this._container;
     //   container.classList.add('mapboxgl-map');

// here is my mapbox new map creation 

const ACCESSTOKEN = < my access token >;
mapboxgl.accessToken = ACCESSTOKEN;
const map2 = new mapboxgl.Map({
  container: 'map2', 
  style: 'mapbox://styles/mapbox/dark-v9',
  center: [0,0], 
  zoom: 8.5, 
  pitch: 45, 
  bearing: 27,
  hash: false
});
&#13;
<!DOCTYPE html>
<html>
 <head>
   <meta charset="UTF-8">
   <title>Mapbox example</title>
   <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />		
   <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.18.0/mapbox-gl.css' rel='stylesheet' />
   <link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v1.1.0/mapbox-gl-geocoder.css' type='text/css' />		
   <link rel="stylesheet" type="text/css" href="css/styles.css">
 </head>
  <body>
    <div id="container">
      <div id="map2"></div>	
    </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.5/leaflet.js">    </script>
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.18.0/mapbox-gl.js'></script>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v1.1.0/mapbox-gl-geocoder.js'></script>
<script type="text/javascript" src="./js/main.min.js"></script>
  </body>
</html>
      
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

此错误表示缺少应包装 mapbox-gl canvas div容器

以下是重现问题的示例:https://jsfiddle.net/kmandov/y933wwys/(您可以在Web控制台中看到错误)

var map = new mapboxgl.Map({
  container: 'map2', // <- missing div!
  style: 'mapbox://styles/mapbox/light-v8',
  center: [12.338, 45.4385],
  zoom: 1
});

您可以看到ID map2的div丢失了。如果您将map2替换为map(现有div的ID),则会按预期显示地图。

在你的情况下,我会验证div map2是否存在,你初始化地图。也许它与你捆绑应用程序的方式有关。

相关问题