I am currently utilizing the Google Maps Javascript API to create a map object on my website. The challenge I am facing is that every time I navigate between pages and return to the map page, the map object gets reinstantiated unnecessarily, resulting in additional API calls. In vanillaJS, I would typically create a global variable for the map.
I am curious about how I can maintain the map object within the session so that revisiting the map page recalls the existing map instead of creating a new one.
The structure of my code resembles the following...
<template>
<div>
<div id="map"></div>
</div>
</template>
<script>
methods: {
onScriptLoaded() {
console.log("Maps API Triggered");
this.map = new window.google.maps.Map(document.getElementById("map"), {
center: new window.google.maps.LatLng(somelat, somelng),
zoom: 11,
...})
}
mounted(){
if (!process.server && !window.google) {
const script = document.createElement("script");
script.onload = this.onScriptLoaded;
script.type = "text/javascript";
script.src =
"https://maps.googleapis.com/maps/api/js?key=<API KEY>&libraries=places";
document.head.appendChild(script);
} else {
this.onScriptLoaded();
}
}
</script>
When returning from a different route (e.g., /about), this.map
is reset to undefined and gets reinitialized when visiting the map page again.
Is there a method to persist the this.map
object so that it retains the map data when coming back to this page?