jand449
jand449

Reputation: 13

Angular 2 Google Maps Javascript API, Route Service function doesn't exist

Trying to get my head around using the Javascript API from Google Maps in my Angular 2 Project.

The problem i have is based on this code:

@Injectable()

export class CalculateAndDisplayRouteService {

public durationTrafficSource = new ReplaySubject<string>();
public durationTraffic$ = this.durationTrafficSource.asObservable();

public changeDurationTraffic(string) {
    this.durationTrafficSource.next(string);
}


public routeResponse(response, status) {
    console.log(response);
    let map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: lat, lng: lng},
        zoom: 8
    });
    if (status === 'OK') {
        let directionsDisplay = new google.maps.DirectionsRenderer({
            suppressMarkers: false,
            suppressInfoWindows: true
        });
        directionsDisplay.setMap(map);
        directionsDisplay.setDirections(response);

        this.changeDurationTraffic(response.routes[0].legs[0].duration.text); //Error is here
    } else {
        window.alert('Directions request failed due to ' + status);
    }
}
private currentDate = new Date();

public route(directionsService, transportMode, origin, destination) {
    if(transportMode === 'DRIVING') {
        directionsService.route({
            origin: origin,
            destination: destination,
            travelMode: transportMode,
            drivingOptions: {
                departureTime: new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), this.currentDate.getDate() + 1, 7, 45),
                trafficModel: 'pessimistic'
            }
        }, this.routeResponse);

The problem I have is in the routeResponse function. I receive an error where the changeDurationTraffic function is called.

"Uncaught TypeError: this.changeDurationTraffic is not a function".

Is there something i am doing wrong? Thanks.

Upvotes: 1

Views: 683

Answers (1)

eko
eko

Reputation: 40677

The this inside that function is not refering to your component because of this method:

public route(directionsService, transportMode, origin, destination) {
    if(transportMode === 'DRIVING') {
        directionsService.route({
            origin: origin,
            destination: destination,
            travelMode: transportMode,
            drivingOptions: {
                departureTime: new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), this.currentDate.getDate() + 1, 7, 45),
                trafficModel: 'pessimistic'
            }
        }, this.routeResponse); //<-- ****Error here.****

Change that line to

this.routeResponse.bind(this);

Suggested reading: How to access the correct `this` context inside a callback?

Upvotes: 2

Related Questions