Access `map` variable in another method

Hi,

My controller code is below:

import { Loader } from “@googlemaps/js-api-loader”
import { Controller } from “@hotwired/stimulus”

export default class extends Controller {
static targets = [“”];

let map;

connect() {
    const loader = new Loader({
        apiKey: "~~~~~~~",
        version: "weekly"
    });

    loader.load().then(() => {
        const worldCenter = new window.google.maps.LatLng(32.249974, 5.800781);

        map = new google.maps.Map(this.element, {
            zoom: 4,
            center: worldCenter,
        });
    });
}

updateMap(data) {
    console.log('UPDATING MAP DATA');

    data.routes.forEach(route => {
        let points = route.points;
        points.forEach(point => {
            const marker = new google.maps.Marker({
                position: new window.google.maps.LatLng(point.lat, point.lng),
                map: map,
            });
        });
    });
}

}

It’s erroring in the update Map method because it states that map is unavailable. How can I access map so I can update the map with new markers and lines etc?

I did try to duplicate the map initialisation inside the updateMap method and this works but it doesn’t seem to be efficient as it’s tearing the whole map down and rebuilding, rather than just updating the existing map i’ve made prior.

1 Like

Anyone able to help me out here?

I think you’re running up against variable hoisting, and how it’s changed over the years. Long ago, declaring a variable would make it available everywhere. In the new class-style code, I think you may need to bind it to the class like this.map in order to get the same behavior.

Walter

1 Like

@walterdavis That’s what worked for me.

This is the only thread I found anywhere that clued me into the @googlemaps/js-api-loader wrapper! Thank you @rctneil !!! It could use a more descriptive title, can you add “google” maybe?