【问题标题】:Vue Google Maps Undefined ErrorsVue Google Maps 未定义错误
【发布时间】:2021-01-15 15:59:37
【问题描述】:

我正在学习使用 Google 地图和 Vue.js 计算两点之间的距离。我试图让一些初始代码用于测试,但不断遇到错误,例如:TypeError: Cannot read property 'LatLng' of undefined

我正在努力弄清楚为什么 vue 不会在如此简单的过程中使用“Google”或“Geometry”。我在 Main.js 中引用了“几何”,但没有运气。我认为我根据其他阅读正确地引用了谷歌,但我正在学习所以谁知道。

<template>
  <div>
   <div><button class='btn-primary' @click='filt'>Filter</button></div>
</div>
</template>


<script>
import * as VueGoogleMaps from 'vue2-google-maps';
export default {
  name: "Distance",
    data: () => {
        return {
          placeholder: "enter location",
            center: {lat: 34.503441, lng: -82.650131},
      targetLoc: { lat: 11.31, lng: 123.89 },
      
        } //ends return
    }, //end data
    methods: {
           filt () {
   
       this.center =  new VueGoogleMaps.gmapApi.maps.LatLng(-36.874694, 174.735292) 
        this.targetLoc = new VueGoogleMaps.gmapApi.maps.LatLng(-36.858317, 174.782284) 
        let distance = VueGoogleMaps.gmapApi.maps.geometry.spherical.computeDistanceBetween(this.center, this.targetLoc) 
      console.log(distance)
      
    },

    },
}
</script>

Main.js 提取

libraries: 'places,drawing,geometry',

上面的代码产生控制台错误: v-on 处理程序中的错误:“TypeError:无法读取未定义的属性 'LatLng'” 任何帮助将不胜感激。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    我已将您的设置更改为:

    <template>
      <div>
        <div><button class='btn-primary' @click='filt'>Filter</button></div>
      </div>
    </template>
    
    
    <script>
    import * as VueGoogleMaps from 'vue2-google-maps';
    export default {
      name: "Distance",
        data: () => {
            return {
              placeholder: "enter location",
              center: {lat: 34.503441, lng: -82.650131},
              targetLoc: { lat: 11.31, lng: 123.89 },
            }
        },
        computed: {
           google: VueGoogleMaps.gmapApi
        },
        methods: {
           filt () {
              this.$gmapApiPromiseLazy().then(() => {
                 this.center = new this.google.maps.LatLng(-36.874694, 174.735292) 
                 this.targetLoc = new this.google.gmapApi.maps.LatLng(-36.858317, 174.782284) 
                 let distance = new this.google.maps.geometry.spherical.computeDistanceBetween(this.center, this.targetLoc) 
                 console.log(distance)
              });
           },
        },
    }
    </script>
    

    this.$gmapApiPromiseLazy().then(() 确保 gmap 对象可以使用,computed: { google: VueGoogleMaps.gmapApi }, 使代码更干净

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 2015-12-17
      相关资源
      最近更新 更多