将Google地图集成到vue.js中 [英] Integrating Google Maps in vue.js
问题描述
I've been trying to initialize a Google map on my vue.js project while including the script :
<script src="https://maps.googleapis.com/maps/api/js?key="MY_API_KEY"&callback=initMap" async defer></script>
问题是我的.vue文件看起来像这样:
The problem is that my .vue files look like that :
<template>
...
</template>
<script>
...
</script>
我的vue文件中不能包含多个脚本标记,我可以显示地图虽然传递了index.html,但我真的不想把js放在index.html上,+我不能在vue方法上指出脚本回调。
And I can't include more than one script tag in my vue file, I can show the map while passing by the index.html but I dont really want to put js on the index.html, + I can't point the script callback on a vue method.
你们有关于如何使用.vue文件显示该地图的一些想法吗?我确实使用了vue2-google-maps,但我想使用原始的Google地图。
Do you guys have some ideas on how to show up that map using a .vue file ? I did use vue2-google-maps but I'd like to use the original google map.
我有一个小提琴,它可以做一些事情: https:/ /jsfiddle.net/okubdoqa/ 而不在脚本标记中使用回调,但它不适用于我......感谢
I have a fiddle which is doing something ok : https://jsfiddle.net/okubdoqa/ without using a callback in the script tag, but it doesnt work for me ... Thanks
推荐答案
在没有使用库的情况下实现这一功能有点繁琐,并且可能有更干净的方法,但是如果您想启动并运行,您可以简单地导入该库并在组件中使用它。
It's a little fussy to get this working without using a library, and there are probably cleaner ways, but you can simply import the library and use it in your components if you want to get up and running.
首先,不要使用 defer
& < script>
标记中的 async
选项。将它加载到 index.html
中:
First, don't use the defer
& async
options in the <script>
tag. Load it in the index.html
:
<script src="https://maps.googleapis.com/maps/api/js?key=yourKey"></script>
然后在您的组件中,您可以访问全局 google
并在组件设置完成后向它传递一个元素。例如,使用Vuejs cli中的设置:
Then in your component you can access the global google
and pass it an element once the component is setup. For example using the setup from the 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>
这篇关于将Google地图集成到vue.js中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!