In this case there is an initMap function in the address_controller.
Alternatively, I could just check that the API has loaded in the connect function and then call initMap, but just wanted to see if there was a way to utilize the URL callback.
I’ll be doing a fair amount of Stimulus/Google Maps, so I’m happy to share what I learn if anyone has questions.
The best way to do this right now is to turn the Google Maps callback into a custom event, and then connect a controller action to listen for that event.
import { Controller } from "stimulus";
import GoogleMapsCallback from "../util/google_maps_callback_helper";
export default class extends Controller {
static targets = ["canvas"];
private canvasTarget: HTMLDivElement;
connect() {
GoogleMapsCallback.ready().then(() => {
this.initGoogleMap();
}).catch(() => {
console.error("Google maps have not been loaded");
});
}
initGoogleMap() {
With this I have promise waiting for window.googleMapCallback to be called and this promise is stored in my google_maps_callback_helper class, which gives actual state of promise to map controller. So in case where map loaded before controller I have in connect already resolved promise, otherwise promise will be resolved later on. Cheers