gpt4 book ai didi

google-maps - 谷歌地图 : Cannot read property 'setDirections' of undefined

转载 作者:搜寻专家 更新时间:2023-10-30 22:30:08 25 4
gpt4 key购买 nike

我是使用 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”值的样子

this.$refs.googleMap.$mapObject value

最佳答案

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.directionsService.route({
    来源:this.location.position,
    目的地:{纬度:62,经度:15},
    旅行模式:'驾驶'
    }, 函数(响应,状态){
    如果(状态==='确定'){
    _self.directionsDisplay.setDirections(响应)
    } 别的 {
    console.log('路线请求因'+状态而失败)
    }
    })

  2. 使用箭头函数进行回调

    getRoute() {
    this.directionsService = new google.maps.DirectionsService()
    this.directionsDisplay = new google.maps.DirectionsRenderer()
    this.directionsDisplay.setMap(this.$refs.googleMap.$mapObject)
    this.directionsService.route({
    来源:this.location.position,
    目的地:{纬度:62,经度:15},
    旅行模式:'驾驶'
    }, (响应, 状态) => {
    如果(状态==='确定'){
    this.directionsDisplay.setDirections(响应)
    } 别的 {
    console.log('路线请求因'+状态而失败)
    }
    })

关于google-maps - 谷歌地图 : Cannot read property 'setDirections' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52846643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com