Javascript 在 vue.js 中集成谷歌地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44634193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:40:06  来源:igfitidea点击:

Integrating Google Maps in vue.js

javascriptgoogle-mapsvue.js

提问by Lo?c Monard

I've been trying to initialize a Google map on my vue.js project while including the script :

我一直在尝试在我的 vue.js 项目上初始化一个谷歌地图,同时包含脚本:

<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 that :

问题是我的 .vue 文件看起来像这样:

<template>
  ...
</template>

<script>
  ...
</script>

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 文件中包含一个以上的脚本标签,我可以在通过 index.html 时显示地图,但我真的不想把 js 放在 index.html 上,+我不能指向脚本vue 方法的回调。

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.

你们对如何使用 .vue 文件显示该地图有一些想法吗?我确实使用了 vue2-google-maps,但我想使用原始的谷歌地图。

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

我有一个小提琴,它正在做一些不错的事情:https: //jsfiddle.net/okubdoqa/没有在脚本标签中使用回调,但它对我不起作用......谢谢

采纳答案by j-printemps

I'd suggest using npm google-mapsinstead of adding a script in index.html. You might not need to call google-maps API in every pages, and I'd say it's better to use Webpack properly. You can use npm install google-maps

我建议使用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
    })
  })
}

回答by Mark Meyer

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.

在不使用库的情况下使其工作有点麻烦,并且可能有更简洁的方法,但是如果您想启动并运行,您可以简单地导入库并在您的组件中使用它。

First, don't use the defer& asyncoptions in the <script>tag. Load it in the index.html:

首先,不要在标签中使用defer&async选项<script>。将其加载到index.html

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

Then in your component you can access the global googleand pass it an element once the component is setup. For example using the setup from the Vuejs cli:

然后在您的组件中,您可以访问全局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>

回答by Vishnu Nair

I was searching for a different issue and found this one, there is another way that you could achieve this without having to add it in index.html.

我正在寻找一个不同的问题并发现了这个问题,还有另一种方法可以实现这一点,而无需将其添加到index.html.

I faced a similar problem where I had to use two Google API keys for different environments so hard-coding it in to index.htmlwas not a good idea, I did this if it helps anyone -

我遇到了一个类似的问题,我不得不在不同的环境中使用两个 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&region=IN`);

      document.body.appendChild(GMap); 
});

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>

It's pretty straightforward, you write a Promise in main.js which will resolve to the callback initiated by Google script ( which we dynamically appended to the body ). Once the Promise is resolved you can access the map object in your component.

非常简单,您在 main.js 中编写了一个 Promise,它将解析由 Google 脚本发起的回调(我们动态地附加到 body 中)。一旦 Promise 被解析,您就可以访问组件中的 map 对象。

回答by ege

There's a different way if you would like to keep the code contained in a Component using the async loader $Scriptjs.

如果您想使用异步加载器 $Scriptjs 保留包含在组件中的代码,则有一种不同的方法。

Install via npm

通过 npm 安装

npm install scriptjs

import into your component

导入到您的组件中

import $Scriptjs from 'scriptjs

load the script in the mounted hook (assuming you have a method in your component called initMap)

在挂载的钩子中加载脚本(假设您的组件中有一个名为 initMap 的方法)

...
mounted () {
  $Scriptjs('https://maps.googleapis.com/maps/api/js?key={YOUR_KEY}', () => {
      this.initMap()
}
...

回答by Niklesh Raut

Initial vue part after Using google map callback function.

使用谷歌地图回调函数后的初始 vue 部分。

function initMap(){ 
 var app = new Vue({
  el:"#app",
  data:{
   name:"Niklesh Raut",
   map:"",
   mapOptions:{}
  },
  mounted(){
   this.initMap();
  },
  methods:{
   initMap: function(){
    this.mapOptions = {
     center: new google.maps.LatLng(21.139808079490507, 79.07690763473511),
     zoom: 10,
     mapTypeId: 'roadmap'
    }
    this.map = new google.maps.Map(document.getElementById("map"), this.mapOptions);
   }
  }
 });
}
.wrapper {
    display: flex;
    width: 100%;
    align-items: stretch;
}
#content {
    width: 100%;
    /*padding: 20px;*/
    min-height: 100vh;
    transition: all 0.3s;
}
.map{
    height: 100%;
    width:100%;
}
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDUFmbwJMBHU_paeMfVO7oqPC1IJEtbJUU&callback=initMap"></script> 
</head> 

<div id="app" class="wrapper">
 <div id="content">
  Name : {{name}}
  <div id="map" class="map"></div>
 </div>
</div>

Jsfiddle Link

Jsfiddle 链接

回答by Max Sherbakov

Best and simple way to integrate Google Maps to Vue is use npm's libs. You need to use vue-google-maps

将 Google Maps 集成到 Vue 的最佳且简单的方法是使用 npm 的库。你需要使用vue-google-maps

npm install vue2-google-maps

then,

然后,

import Vue from 'vue'
import * as VueGoogleMaps from 'vue2-google-maps'

Vue.use(VueGoogleMaps, {
  load: {
    key: 'YOUR_API_TOKEN',

  },


})

Just simple paste code below:

只是简单的粘贴代码如下:

<GmapMap
  :center="{lat:10, lng:10}"
  :zoom="7"
  map-type-id="terrain"
  style="width: 500px; height: 300px"
>


</GmapMap>