gpt4 book ai didi

javascript - Angular 2 Google Maps Javascript API,路由服务功能不存在

转载 作者:行者123 更新时间:2023-11-30 15:24:46 25 4
gpt4 key购买 nike

尝试在我的 Angular 2 项目中使用来自 Google map 的 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 函数时收到错误。

“未捕获的类型错误:this.changeDurationTraffic 不是函数”。

我做错了什么吗?谢谢。

最佳答案

由于此方法,该函数内的 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?

关于javascript - Angular 2 Google Maps Javascript API,路由服务功能不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164426/

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