mapbox gl js – 未捕获TypeError:无法读取null的属性'classList'

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

Uncaught TypeError:无法读取null的属性'classList'。

我不知道为什么会发生这种情况,因为我在我的html中创build了元素,而且我的javascript与在index.html页面(但在不同div上)成功创build第一个映射的javascript完全相同。 我在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 }); 
 <!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> 

此错误表示应该包裹mapbox-glcanvasdiv容器丢失。

这里是一个重现问题的例子: 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丢失。 如果将map2replace为map (现有div的id), map2预期显示地图。

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