我是使用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
这是我实现了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”值的样子
答案 0 :(得分:5)
this
指的是回调函数,因为您没有使用箭头函数,有两种方法
在将函数与回调一起使用之前,将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)
}
})
使用箭头函数进行回调
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)
}
})
答案 1 :(得分:1)
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)
}
})