Reputation: 475
Im using MapBox in one of my web aplicatins, nad my goal is to render a basic map on the page.
I have the following script:
<script>
mapboxgl.accessToken = mapToken;
const map = new mapboxgl.Map({
container: 'map', // container ID
style: 'mapbox://styles/mapbox/streets-v11', // style URL
center: [-74.5, 40], // starting position [lng, lat]
zoom: 9 // starting zoom
});
</script>
and to display the map, I use:
<div id='map' style='width: 400px; height: 300px;'></div>
The problem is, when I try to load the page, nothing happens and I get the following error: Uncaught ReferenceError: mapboxgl is not defined
Upvotes: 4
Views: 7353
Reputation: 1
2024 update
v2.9.1 has more security and requires accurate header configurations to work. In my node js and express app, using helmet to set http headers this is the configuration that worked for me.
const helmet = require('helmet');
// ...
app.use(
helmet({
contentSecurityPolicy: {
directives: {
// ... other directives
"script-src": [
"'self'", // allow scripts from your own domain
"'unsafe-inline'", // allow inline scripts (you may want to remove this depending on your needs)
"https://api.mapbox.com", // allow scripts from the Mapbox CDN
],
"worker-src": [
"'self'", // allow web workers from your own domain
"http://localhost:3000", // allow web workers from the current host (development environment)
"https://api.mapbox.com", // allow web workers from the Mapbox CDN
"blob:" // allow web workers from blob URLs
],
"connect-src": [
"'self'", // allow connections to your own domain
"https://api.mapbox.com", // allow connections to the Mapbox API
"https://events.mapbox.com" // allow connections to Mapbox events
],
},
},
})
);
// ...
refer to older version v0.54.0, to have it run without errors and without header configurations.
Upvotes: 0
Reputation: 467
Also you add this to your block
head
of your pug file if you're doing templating with pug
library.
script(src='https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.js')
link(href='https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.css' rel='stylesheet')
Upvotes: 0
Reputation: 155
2022 Update
This was what worked for me
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v2.9.2/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v2.9.2/mapbox-gl.css' rel='stylesheet' />
Upvotes: 0
Reputation: 475
I fixed the problem just by including this:
<script src='https://api.mapbox.com/mapbox-gl-js/v2.6.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v2.6.0/mapbox-gl.css' rel='stylesheet' />
in the head of the HTML file.
Upvotes: 4