Google Maps integration in vue.js

I am trying to initialize a Google map in my vue.js project, including a script:

<script src="https://maps.googleapis.com/maps/api/js?key="MY_API_KEY"&callback=initMap" async defer></script> 

The problem is that my .vue files look like this:

 <template> ... </template> <script> ... </script> 

And I can’t include more than one script tag in my vue file, I can show the map when passing through index.html, but I really don’t want to put js in index.html, + I can’t specify the script callback on the vue method.

Do you have any ideas on how to display this map using a .vue file? I used vue2-google maps, but I would like to use the original google map.

I have a fiddle that does something good: https://jsfiddle.net/okubdoqa/ without using the callback in the script tag, but it does not work for me ... Thanks

+5
source share
2 answers

It's a little fussy for this to work without using a library, and there may be cleaner ways, but you can just import the library and use it in your components if you want to get started.

First, do not use the defer and async parameters in the <script> . Download it in index.html :

 <script src="https://maps.googleapis.com/maps/api/js?key=yourKey"></script> 

Then in your component you can access the global google and pass the element to it after installing the component. For example, using the setting from Vuejs cli:

 <template> <div class="hello"> <h1>{{ msg }}</h1> <div id="myMap"></div> </div> </template> <script> export default { name: 'hello', data () { return { msg: 'Welcome to Your Vue.js App' }}, mounted: function() { console.log("map: ", google.maps) this.map = new google.maps.Map(document.getElementById('myMap'), { center: {lat:61.180059, lng: -149.822075}, scrollwheel: false, zoom: 4 }) } } </script> <style scoped> #myMap { height:300px; width: 100%; } </style> 
+3
source

I suggest using npm google-maps instead of adding a script to index.html. You may not need to call google-maps APIs on all pages, and I would say that it is better to use Webpack correctly. You can use npm install google-maps

 import GoogleMapsLoader from 'google-maps' mounted: function () { GoogleMapsLoader.load(function(google) { let map = new google.maps.Map(document.getElementById('map'), { zoom: 15, center: position }) }) } 
+9
source

Source: https://habr.com/ru/post/1268994/


All Articles