Since Mapboxgl requires a container in the HTML that loads the Javascript file, is it possible to access the map from another Javascript file? For example, here's a simple use case where there's two different html pages, each having it's own scripts, in which I'll be trying to add data to the map from the first html page (but doing so I would need access to the mapboxgl variable):
page2.html
<div id="map"></div>
<script src="page2.js"></script>
page2.js:
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v8', //stylesheet location
center: [-74.50, 40], // starting position
zoom: 9 // starting zoom
});
function update(map) {
console.log(map);
}
In my page1.js, I want to access that map variable. There should be no map on page1.html because I will not be creating a mapbox object in page1.js. Is there a way to access the map variable in page2.js from page1.js? I tried including the page2.js script in my page1.html so I could use the update function, but doing that gives me an error because I do not have a div container with the id 'map' on page1.html. Basically, when I try to access the map variable it always tries to find the container.
Uncaught TypeError: Cannot read property 'classList' of null
page1.html
<script src="page2.js"></script>
<script src="page1.js"></script>
page1.js
update(map); (will give me error when I try to use the addSource function in the API because 'map' is null)
Not sure if this is more of a Javascript issue or a Mapbox issue, but would greatly appreciate any suggestions on how to solve the problem I'm having.
Thanks for using Mapbox GL! This is purely a JavaScript issue though, so you're more likely to find an answer on StackOverflow.
If anyone in the future lands here from Google with this same problem, I found this StackOverflow post to be helpful
tl;dr: put your script at the bottom of the page so the DOM can load first. Then all the elements should be accessible in your JS
Most helpful comment
If anyone in the future lands here from Google with this same problem, I found this StackOverflow post to be helpful
tl;dr: put your script at the bottom of the page so the DOM can load first. Then all the elements should be accessible in your JS