Googe Maps:无法读取未定义的属性'setDirections'

Riy*_*enz 2 google-maps google-api directions vue.js vuejs2

我是使用Google Maps 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
Run Code Online (Sandbox Code Playgroud)

这是我实现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)
    }
  })
},
Run Code Online (Sandbox Code Playgroud)

这就是'this.$ refs.googleMap.$ mapObject'的值

这个.$ refs.googleMap.$ mapObject值

one*_*man 7

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) } })