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
         });
    }
});
9
  • Please provide your component's code. Commented Jan 13, 2018 at 11:04
  • code sample updated Commented Jan 13, 2018 at 11:13
  • This has been already answered: stackoverflow.com/questions/44634193/… Commented Jan 13, 2018 at 11:18
  • 1
    TL;DR: you're using async loading, that's why GMaps is not available at the mounted hook yet. It's still loading. Commented Jan 13, 2018 at 11:18
  • but working when refreshing the page by pressing ctrl+f5 Commented Jan 13, 2018 at 11:27

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

The problem with loading the maps API from index.html is having different keys for development and production as recommended by Google.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.