【问题标题】:VUE + google map how include api googleVUE + google map 如何包含api google
【发布时间】:2017-07-05 23:28:05
【问题描述】:

我开始使用 vue。如何在我的页面中包含 Google API?这是我的代码:

<template>
    <div id="map"></div>
</template>

 <script>

export default {
methods: {
  init () {
    var map
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 16,
      center: new google.maps.LatLng(-33.91722, 151.23064),
      mapTypeId: 'roadmap'
    })
  }
}
}

</script>

哪里可以设置

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

【问题讨论】:

  • this 可能会有所帮助

标签: javascript google-maps vue.js


【解决方案1】:

脚本元素进入您的 index.html 文件,例如:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id="app"></div>
  </body>
  <script src="https://maps.googleapis.com/maps/api/js?key=YourKey&callback=App.map" async defer></script>
</html>

如果这对您不起作用,请尝试从 &lt;script&gt; 元素的 src 属性以及 async 和 defer 关键字末尾删除回调,如下所示:

&lt;script src="https://maps.googleapis.com/maps/api/js?key=YourKey"&gt;&lt;/script&gt;

然后在您的 vue 实例中,在 App 组件挂载后调用您的 init() 函数。见下文:

export default {
  mounted () {
    this.init()
  },
  methods: {
    init () {
      var map
      map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: new google.maps.LatLng(-33.91722, 151.23064),
        mapTypeId: 'roadmap'
      })
    }
  }
}

【讨论】:

  • 试着像你说的那样做...... 14:19 错误 'google' is not defined no-undef
  • 我假设您使用带有 JavaScript linter 的单个文件组件。您收到该错误是因为当 linter 检查单个文件组件时,它没有在任何地方看到“google”定义,但您正在引用它。这很好,因为我们知道它是由 index.html 加载的。您可以通过在 &lt;script&gt; 部分的 export default { 行上方添加 /* eslint-disable no-undef */ 来抑制错误消息。
  • hm...我刚开始使用global ty 来回答所有问题
【解决方案2】:

我想将 google map api 放在 &lt;/body&gt; 之前。确保您的 vue 元素在 google map api 之前被调用(即在 app.js 中)。把initMap作为google api的回调。

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id="app">
      <map lat="1.23456" lng="100.21345"></map>
    </div>
    <script src="app.js"></script><!-- your vue element should be here -->
    <script src="https://maps.googleapis.com/maps/api/js?key=YourKey&callback=initMap" async defer></script>
  </body>
</html>

这是我在Map.vue 中的代码,它的定义为window.initMap(..)。我在地图内也有一个标记(大头针)。

<template>
  <div>
    <div ref="map" style="width: 100%; height: 200px;"></div>
  </div>
</template>

export default {
  props: [
    'lat', 
    'lng'
  ],
  mounted() {
    window.initMap = () => {

      this.mapElement = new google.maps.Map(this.$refs.map, {
        zoom: 14,
        center: {lat: this.lat, lng: this.lng}
      });

      this.marker = new google.maps.Marker({
        position: {lat: this.lat, lng: this.lng},
        map: this.mapElement
      });
    }
  },
  data() {
    return {
      mapElement: null,
      marker: null
    }
  }
}

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多