Search code examples
google-mapsvue.jsgoogle-apivuejs2directions

Googe Maps: Cannot read property 'setDirections' of undefined


I'm a beginner on using Google Maps API and I just want some help with regards with my error below:

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

Here's my code that implements the 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)
    }
  })
},

And this is what the 'this.$refs.googleMap.$mapObject' value looks like

this.$refs.googleMap.$mapObject value


Solution

  • this refers to the function in callback since you are not using arrow function for that, there are a 2 approaches for that

    1. Assign the this to a variable before using the function with callback:

      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. Use arrow function for the callback

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