So basically I initialize an object within onMount like this-
onMount(() => {
const mapy = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/satellite-v9",
center: testCoords[0],
zoom: 19,
});
console.log(mapy);
});
Then outside I have-
function AddPoint(){
Center=mapy.getCenter;
}
AddPoint is called from a HTML button. I get this error in the console- Uncaught ReferenceError: mapy is not defined
I only press the button after it has been initialized, and I know it has been initialized because of my console.log() inside onMount
This is a straightforward scope error. When you declare mapy inside onMount (const mapy = ...), you make mapy local to onMount in scope, meaning it is undefined outside of onMount.
What you want to do here is declare mapy at the top level of your script, then assign to it inside onMount:
let mapy;
onMount(() => {
mapy = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/satellite-v9",
center: testCoords[0],
zoom: 19,
});
console.log(mapy);
});
function AddPoint() {
Center = mapy ? mapy.getCenter : undefined;
}