What methods can I utilize from Google Maps within Vuex's createStore()?

Currently, I am in the process of configuring my Vuex store to hold an array of Marker objects from the Google Maps Javascript API. Here is a snippet of how my createStore function appears:

import { createStore } from "vuex";
    
export default createStore({
  state: {
    GCPMarkers: {
      basemapMarkers: [new google.maps.Marker()],
      mosaicMarkers: [new google.maps.Marker()],
    },
  },
  // other properties
});

The initialization of the Google Maps Javascript API takes place within a Vue component named Map on my Home page:

// Inside Map.vue
mounted() {
  const loader = new Loader({
    apiKey: "my key",
    version: "weekly",
  });
    
  loader
    .load()
    .then(this.initMap)
    .catch((e) => console.log(e));
},

In addition, my main.ts file looks like this:

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

createApp(App).use(store).use(router).mount("#app");

Upon running my application, an error message regarding

basemapMarkers: [new google.maps.Marker()],
is displayed:

Uncaught ReferenceError: google is not defined

I understand that this issue arises due to the fact that the google object has not been loaded at the time when the

import store from "./store"
line is executed. However, determining the correct solution remains a challenge for me.

One possible resolution I thought of involves transferring the loader code to my main.ts file so that until the promise returned by loader is fulfilled, the importation of other files does not commence. Despite that, this approach seems inelegant and may not be the optimal way to go about it.

Answer №1

For the proper functioning of your app, it is essential that google is defined and loaded by Loader. To ensure this, you should delay creating the app until after Loader has finished its task. In the scenario where the load() function successfully assigns the global object google, you can proceed to create the app within the callback of that Promise:

// main.ts
import { createApp } from 'vue'
import App from './App.vue'

const loader = new Loader({
  apiKey: "my key",
  version: "weekly",
});
    
loader
  .load()
  .then(() => {
    const store = require('./store').default
    createApp(App)
      .use(store) // now safe to use store as `google` is loaded
      .mount('#app');
  })
  .catch((e) => console.log(e));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What's the best way to add line numbers to source code on an HTML webpage after parsing?

I am currently working with AngularJS and MongoDB. In my MongoDB data, there are some text elements that contain a \n, causing each line to be displayed on a new line based on the occurrence of \n. However, I also want to add line numbers to each ...

Encountering an issue with WebRTC where the 'addIceCandidate' function on RTCPeerConnection is failing, resulting in an error displayed on the console. However, despite this error

I am facing an issue with connecting two peers using webRTC. While I can successfully display both local and remote videos, as soon as the remote video appears, the candidate object turns null and an error message is logged on the console. TypeError: Fail ...

Countdown with precision! This timer will begin at the one-hour mark

Having an issue with my JavaScript stopwatch. When I hit the start button, the stopwatch immediately shows one hour (01:00:00) before counting normally. Any solutions to prevent this instant start at one hour would be highly appreciated. Thank you in adv ...

Is it possible to verify or authenticate the properties received directly from the associated type or interface?

Looking for a more efficient way to handle validation in my component that takes an array of tabs and children as props. I would like to check if the children provided are the same length as the tabs array directly from the type declaration or any cleaner ...

Create a personalized form with HTML and JQuery

Currently, the data is displayed on a page in the following format: AB123 | LHRLAX | J9 I7 C9 D9 A6 | -0655 0910 -------------------------------------------------------- CF1153 | LHRLAX | I7 J7 Z9 T9 V7 | -0910 1305 ---------------- ...

When URL string parameters are sent to an MVC controller action, they are received as null values

Are You Using a Controller? public class MyController : Controller { [HttpGet] public ActionResult MyAction(int iMode, string strSearch) { return View(); } } Within my view, I have a specific div with the id of "center" I am runn ...

Using Python with Selenium and JavaScript for Logging in

When using Selenium and Python, I am attempting to log in to a website but encountering difficulties. The issue is that the source code does not display the necessary Id=apple_Id required for sending login information, although it can be seen when inspecti ...

Is there a way to conceal a slice of a pie chart in HighCharts without excluding it from the legend display?

I've been searching everywhere for a solution to this issue, but I just can't seem to pinpoint where I'm going wrong. My goal is to initiate a pie chart using HighCharts with specific slices hidden as if they were "clicked" off in the legen ...

Issue found: Passing a non-string value to the `ts.resolveTypeReferenceDirective` function

Encountering the following error: Module build failed (from ./node_modules/ts-loader/index.js): Error: Debug Failure. False expression: Non-string value passed to ts.resolveTypeReferenceDirective, likely by a wrapping package working with an outdated res ...

How to prevent checkbox autocomplete from selecting the previously checked value using Jquery Ajax

Working on implementing the "Autocomplete ajax search" feature using Php. Successfully fetching data from the database. Currently, when searching for something, the results with checkboxes are displayed. However, when I search for a text, check a checkbo ...

Issue with undefined bindingContext.$data in IE9 on knockout binding handler

I'm attempting to create a unique binding handler that applies role-based access to fields on a page. This custom handler uses the values of other observables from the viewModel to enable or disable input controls based on certain conditions. However ...

Unable to be implemented using inline-block styling

I'm struggling to get these 2 elements to display side by side using inline-block, I've tried everything but nothing seems to work. Goal: First element Second element I attempted to modify the HTML code to see if it would yield any results, b ...

Executing Backbone.history.start() prevents the back button from navigating away from the current page

I've encountered this issue in multiple apps, leading me to question if there's an error in my handling of Backbone history. The scenario is as follows... There are two pages: index.html app.html The index page is a standard HTML page with a l ...

How can an external style sheet be inserted into an iframe?

My website features an editor on one side and an iframe on the other. Currently, anytime HTML code is entered into the editor and a keyup event occurs, the iframe updates automatically. I am looking to add default styling to the code entered in the editor ...

Troubleshooting: :before element not being hidden by jQuery slidetoggle()

My elements are all behaving correctly with the slidetoggle() function, except for my li:before class. I've attempted to manipulate the overflow, visibility, display, and other properties of both the :before pseudo-element and the li element, but the ...

The lightbox fails to display in IE when a synchronous ajax request is triggered

I have a piece of code that displays a lightbox with the message 'Please Wait', followed by a synchronous ajax request that removes the lightbox once it's completed. This setup works perfectly in most browsers, but in Internet Explorer, the ...

Ways to retrieve an array saved in another JavaScript document

I am in the process of developing my own lorem ipsum application and keen on maintaining clean code by storing my word bank in separate files. How can I retrieve an array stored in a different JavaScript file? Rather than manually inputting harry = ["", "" ...

How to trigger an Angular (ionic) view update following an HTTP post request

Is there a way to update the expression in my view after making an HTTP post request? I have tried using the $scope.$apply function, but it gives me an error from ionic.bundle.js saying "$digest already in progress". Could this be a mistake on my part or ...

Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using import * as JsSearch from 'js-search';, but I keep getting a Uncaught TypeError: Failed to resolve module specifier "js-se ...

What is the best way to retrieve the current directory of the executed javascript file?

My javascript file is located in a folder at this path: /httpdocs/wp-content/themes/themeName/users/js I have some PHP files in another directory within the same theme, where I need to send Ajax Requests: /httpdocs/wp-content/themes/themeName/users Is ...