Loï*_*ard 19 javascript google-maps vue.js
我一直在尝试在我的vue.js项目中初始化Google地图,同时包含脚本:
<script src="https://maps.googleapis.com/maps/api/js?key="MY_API_KEY"&callback=initMap" async defer></script>
Run Code Online (Sandbox Code Playgroud)
问题是我的.vue文件看起来像这样:
<template>
...
</template>
<script>
...
</script>
Run Code Online (Sandbox Code Playgroud)
而且我不能在我的vue文件中包含多个脚本标记,我可以在通过index.html时显示地图但是我真的不想把js放在index.html上,+我不能指向脚本回调vue方法.
你们对如何使用.vue文件显示该地图有一些想法吗?我确实使用了vue2-google-maps,但我想使用原始的谷歌地图.
我有一个小提琴正在做一些事情:https://jsfiddle.net/okubdoqa/没有在脚本标签中使用回调,但它对我不起作用...谢谢
j-p*_*mps 19
我建议使用npm google-maps而不是在index.html中添加脚本.您可能不需要在每个页面中调用google-maps API,我会说最好正确使用Webpack.您可以使用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
})
})
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*yer 14
在不使用库的情况下让它工作有点挑剔,并且可能有更简洁的方法,但是如果你想要启动并运行,你可以简单地导入库并在组件中使用它.
首先,不要在标签中使用defer&async选项<script>.加载到index.html:
<script src="https://maps.googleapis.com/maps/api/js?key=yourKey"></script>
Run Code Online (Sandbox Code Playgroud)
然后在组件中,您可以访问全局,google并在设置组件后将其传递给元素.例如,使用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>
Run Code Online (Sandbox Code Playgroud)
Vis*_*air 11
我正在寻找一个不同的问题并找到了这个问题,还有另一种方法可以实现这一点而无需添加它index.html.
我遇到了类似的问题,我不得不为不同的环境使用两个Google API密钥,因此对其进行硬编码index.html并不是一个好主意,如果有帮助的话,我会这样做 -
main.js
export const loadedGoogleMapsAPI = new Promise( (resolve,reject) => {
window['GoogleMapsInit'] = resolve;
let GMap = document.createElement('script');
GMap.setAttribute('src',
`https://maps.googleapis.com/maps/api/js?key=${process.env.GOOGLE_API_KEY}&callback=GoogleMapsInit®ion=IN`);
document.body.appendChild(GMap);
});
Run Code Online (Sandbox Code Playgroud)
MapElem.vue
<template>
<div id="map"></div>
</template>
<script>
import {loadedGoogleMapsAPI} from '@/main'
export default {
name: 'MapEl',
mounted(){
loadedGoogleMapsAPI.then(()=>{
this.initMap()
});
},
methods:{
initMap(){
console.log(google.maps); //You can now access google maps object here
new google.maps.Map(document.getElementById('map'), {
// You configuration goes here
})
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
这非常简单,你在main.js中写了一个Promise,它将解析为由Google脚本(我们动态附加到正文)启动的回调.解决Promise后,您可以访问组件中的地图对象.
| 归档时间: |
|
| 查看次数: |
18484 次 |
| 最近记录: |