VueJS,ReferenceError:未定义谷歌

新手上路,请多包涵

我有以下源代码,当我尝试使用 google.maps ... 实例化一个新的 var 时,我也遇到了以下错误:

谷歌’未定义

许多答案都谈到在其他所有内容之前异步加载 API 脚本,脚本的顺序很重要,但我认为这不是我的问题。

PS:我在 main.js

 Vue.use(VueGoogleMaps, {
  load: {
    key: 'MY-KEY',
    libraries: 'places', //// If you need to use place input
  },
})

谁能帮我?谢谢。

 <div class="map-container">
       <gmap-map
         id="map"
         ref="map"
         :center="center"
         :zoom="15"
         map-type-id="roadmap"
         style="width:100%;  height: 400px;">
           <gmap-marker
           :key="index"
            v-for="(m, index) in markers"
            :position="m.position"
             @click="center=m.position"
             ></gmap-marker>
                </gmap-map>
            </div>

 <script>
    import _ from 'lodash'
    import { mapState } from 'vuex'
    import * as VueGoogleMaps from 'vue2-google-maps'

    export default {
      computed: {
        ...mapState([
          'map',
        ]),
        mapStyle: function () {
          const h = document.body.clientHeight - 80
          return 'width: 100%; height: ' + h + 'px'
        },
        center: function () {
          return { lat: 44.837938, lng: -0.579174 }
        },
      },
      mounted: function () {
        VueGoogleMaps.loaded.then(() => {
           var map = new google.maps.Map(document.getElementById('map'))
        }
      },

原文由 Smix 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 463
2 个回答

由于您已将所有内容导入为 VueGoogleMaps 我假设 google 在此对象内。

编辑:似乎 google 对象被称为 gmapApi

所以改变

var map = new google.maps.Map(document.getElementById('map'))

let map = new VueGoogleMaps.gmapApi.maps.Map(document.getElementById('map'))

由于您没有明确导入任何内容,因此它应该全部位于 VueGoogleMaps 内。因此,如果您想将其命名为 google ,请按照其他答案中的说明添加计算字段,除了 gmapApi 应该位于 VueGoogleMaps

所以

computed: {
    google: VueGoogleMaps.gmapApi
}

原文由 Matthias S 发布,翻译遵循 CC BY-SA 4.0 许可协议

你忘了一个括号:

 VueGoogleMaps.loaded.then(() => {
           var map = new google.maps.Map(document.getElementById('map'))
        })

告诉我这是否有帮助。


同样来自 NPM vue2-google-maps

如果您需要访问 google 对象:

 <template>
  <GmapMarker ref="myMarker"
    :position="google && new google.maps.LatLng(1.38, 103.8)" />
</template>
<script>
import {gmapApi} from 'vue2-google-maps'

export default {
  computed: {
    google: gmapApi
  }
}
</script>

原文由 charlycou 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏