Angular 2 Google Maps Javascript API,路径服务功能不存在

时间:2017-04-02 03:45:18

标签: javascript google-maps angular

尝试在我的Angular 2项目中使用Google地图中的Javascript API。

我遇到的问题基于以下代码:

@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);

我遇到的问题是routeResponse函数。我收到一个错误,其中调用changeDurationTraffic函数。

“未捕获的TypeError:this.changeDurationTraffic不是函数”。

我有什么问题吗?感谢。

1 个答案:

答案 0 :(得分:2)

由于此方法,该函数内的this未引用您的组件:

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.****

将该行更改为

this.routeResponse.bind(this);

建议阅读:How to access the correct `this` context inside a callback?