Google maps 谷歌地图:无法读取属性';设置方向';未定义的

Google maps 谷歌地图:无法读取属性';设置方向';未定义的,google-maps,vue.js,google-api,vuejs2,directions,Google Maps,Vue.js,Google Api,Vuejs2,Directions,我是一个使用谷歌地图API的初学者,我只是想得到一些关于我以下错误的帮助: Uncaught TypeError: Cannot read property 'setDirections' of undefined at eval (google-maps.vue?1cba:101) at directions.js:8 at gm.j (directions.js:5) at Object.c [as _3lwmum] (common.js:46) at VM1924 DirectionsSe

我是一个使用谷歌地图API的初学者,我只是想得到一些关于我以下错误的帮助:

Uncaught TypeError: Cannot read property 'setDirections' of undefined
at eval (google-maps.vue?1cba:101)
at directions.js:8
at gm.j (directions.js:5)
at Object.c [as _3lwmum] (common.js:46)
at VM1924 DirectionsService.Route:1
下面是我实现Directions API的代码

getRoute() {
  this.directionsService = new google.maps.DirectionsService()
  this.directionsDisplay = new google.maps.DirectionsRenderer()
  this.directionsDisplay.setMap(this.$refs.googleMap.$mapObject)
  this.directionsService.route({
    origin: this.location.position,
    destination: { lat: 62, lng: 15 },
    travelMode: 'DRIVING'
  }, function (response, status) {
    if (status === 'OK') {
      this.directionsDisplay.setDirections(response)
    } else {
      console.log('Directions request failed due to ' + status)
    }
  })
},
这就是'this.$refs.googleMap.$mapObject'值的样子


函数回调中的此
不同。这不是Vue实例

您可以使用以下技巧:

getRoute() {
  this.directionsService = new google.maps.DirectionsService()
  this.directionsDisplay = new google.maps.DirectionsRenderer()
  this.directionsDisplay.setMap(this.$refs.googleMap.$mapObject)
  var self = this
  this.directionsService.route({
    origin: this.location.position,
    destination: { lat: 62, lng: 15 },
    travelMode: 'DRIVING'
  }, function (response, status) {
    if (status === 'OK') {
      self.directionsDisplay.setDirections(response)
    } else {
      console.log('Directions request failed due to ' + status)
    }
  })

引用回调函数,因为您没有使用arrow函数,所以有两种方法

  • 在使用回调函数之前,将
    分配给变量:

    getRoute(){
    this.directionsService=new google.maps.directionsService()
    this.directionsDisplay=new google.maps.DirectionsRenderer()
    this.directionsDisplay.setMap(this.$refs.googleMap.$mapObject)
    const_self=这个
    此路径为.DirectionService.route({
    来源:this.location.position,
    目的地:{lat:62,lng:15},
    travelMode:“驾驶”
    },功能(响应、状态){
    如果(状态=='OK'){
    _self.directions显示.setDirections(响应)
    }否则{
    console.log('由于'+状态,方向请求失败)
    }
    })
    

  • 对回调函数使用arrow函数

    getRoute(){
    this.directionsService=new google.maps.directionsService()
    this.directionsDisplay=new google.maps.DirectionsRenderer()
    this.directionsDisplay.setMap(this.$refs.googleMap.$mapObject)
    此路径为.DirectionService.route({
    来源:this.location.position,
    目的地:{lat:62,lng:15},
    travelMode:“驾驶”
    },(响应、状态)=>{
    如果(状态=='OK'){
    this.directionsDisplay.setDirections(响应)
    }否则{
    console.log('由于'+状态,方向请求失败)
    }
    })