Google 地图:无法读取未定义的 属性 'setDirections'

Googe Maps: Cannot read property 'setDirections' of undefined

我是使用 Google 地图 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

这是我实现指令的代码 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' 值的样子

this 在函数回调中是不同的。这不是 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)
    }
  })

this 指的是回调中的函数,因为您没有为此使用箭头函数,因此有两种方法

  1. 在使用回调函数之前将 this 分配给一个变量:

    getRoute() { this.directionsService = new google.maps.DirectionsService() this.directionsDisplay = new google.maps.DirectionsRenderer() this.directionsDisplay.setMap(this.$refs.googleMap.$mapObject) const _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) } })

  2. 回调使用箭头函数

    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' }, (response, status) => { if (status === 'OK') { this.directionsDisplay.setDirections(response) } else { console.log('Directions request failed due to ' + status) } })