解决Uncaught ReferenceError: mapboxgl未定义及Mapbox地图无法显示问题
Uncaught ReferenceError: mapboxgl is not defined 错误排查与修复
问题背景
控制台抛出Uncaught ReferenceError: mapboxgl is not defined错误,网页无法正常显示Mapbox地图,排查数小时未定位问题。相关代码如下:
Pug 模板代码
doctype html html head block head meta(charset='UTF-8') meta(name='viewport' content='width=device-width, initial-scale=1.0' value="script-src 'self' api.mapbox.com") link(rel='stylesheet' href ='/css/style.css') link(rel='shortcut icon' type='image/png' href='/img/favicon.png') link(rel='stylesheet' href='https://fonts.googleapis.com/css?family=Lato:300,300i,700') title Natours | #{title} body //HEADER include _header //CONTENT block content h1 This is a placeholder heading //FOOTER include _footer script(src='/js/mapbox.js')
自定义 JS 代码(/js/mapbox.js)
/* eslint-disable */ const locations = JSON.parse(document.getElementById("map").dataset.locations); mapboxgl.accessToken = 'xxxxxx'; var map = new mapboxgl.Map({ container: 'map', style:'mapbox://styles/mapbox/streets-v11',, });
地图容器代码(Pug 片段)
section.section-map #map(data-locations=`${JSON.stringify(tour.locations)}`)
问题分析
错误的核心原因是浏览器执行自定义JS时,全局对象mapboxgl未被定义,具体诱因包括:
- 缺失Mapbox核心库引入:仅加载了自定义的
mapbox.js,未引入Mapbox官方提供的GL JS SDK,导致mapboxgl对象不存在 - CSP元标签配置错误:错误地在
viewport元标签中添加CSP规则,既无效又可能干扰脚本加载逻辑 - JS语法错误:地图初始化代码中
style属性后多了一个逗号,会导致JS解析失败,进一步阻断地图加载流程
修复方案
1. 引入Mapbox核心库
在Pug模板的body末尾、自定义mapbox.js之前,添加Mapbox官方脚本与样式:
script(src='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js') link(rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css')
可根据需求替换为最新版本的Mapbox GL JS
2. 修复CSP配置(可选)
移除原viewport标签中的无效value属性,恢复正确的viewport配置;若需启用内容安全策略,添加独立的CSP元标签:
meta(name='viewport' content='width=device-width, initial-scale=1.0') meta(http-equiv='Content-Security-Policy' content="script-src 'self' api.mapbox.com; style-src 'self' api.mapbox.com; img-src 'self' data: mapbox.com")
3. 修正JS语法错误
删除地图初始化代码中style属性后的多余逗号:
/* eslint-disable */ const locations = JSON.parse(document.getElementById("map").dataset.locations); mapboxgl.accessToken = 'xxxxxx'; var map = new mapboxgl.Map({ container: 'map', style:'mapbox://styles/mapbox/streets-v11' });
4. 验证地图容器存在
确保地图容器代码渲染后生成的HTML包含<div id="map" data-locations="..."></div>,由于脚本在body末尾加载,容器会先于JS执行完成渲染,此条件默认满足。
内容的提问来源于stack exchange,提问作者xitij
相关产品推荐
相关产品推荐

