0

Google map not loading property unless I press ctrl+f5. I initialise map inside vue js mounted hook. The error displayed is

Error in mounted hook: "ReferenceError: google is not defined"

when I press ctrl+f5 everything works fine

<div id="map"></div>

<script src="https://maps.googleapis.com/maps/api/js?key=****"
            async defer></script>
new Vue({
    el:'#app',
    mounted() {
         map = new google.maps.Map(document.getElementById('map'), {
             center: {lat: -34.397, lng: 150.644},
             zoom: 8
         });
    }
});
Rahul Reghunath
  • 1,210
  • 13
  • 23

1 Answers1

0

I'd suggest using existing Google Maps libraries for Vue, but if you insist on loading Google Maps asynchronously as is:

new Vue({
    el:'#app',
    created() {
         let script = document.createElement('script');
         script.src = 'https://maps.googleapis.com/maps/api/js?key=****';
         document.body.appendChild(script);
         script.load = function(){  
             map = new google.maps.Map(document.getElementById('map'), {
                 center: {lat: -34.397, lng: 150.644},
                 zoom: 8
             });
         };
    }
});

Basically you have to listen for a load event to start working with API.

But I feel like in your case the best practice would be to load it synchronously before your Vue.js app even loads since it's probably fully reliant on Google Maps API:

<html>
<body>
...
    <script src="https://maps.googleapis.com/maps/api/js?key=****"></script>
    <script src="path-to-your-app's-js"></script>
</body>
</html>
CyberAP
  • 1,195
  • 1
  • 11
  • 17
  • The problem with loading the maps API from index.html is having different keys for development and production as recommended by Google. – Alien Technology Mar 20 '19 at 21:22