我正在使用Angular 6使用Google Maps Directions API来启动带有方向的google map。在实现代码之后。控制台显示以下错误:
未捕获(已承诺) Jc {消息:“ initMap不是函数”,名称:“ InvalidValueError”,堆栈:“新Jc的错误↵(https://maps.googleapis.com/m…F5xxXLWf2ZqIDEfUDitY7Ncs&callback = initMap:123:108“}} 信息 : “ initMap不是函数” 名称 : “ InvalidValueError”
home.component.ts:
import { Component, OnInit } from '@angular/core';
declare var google: any;
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['../../resources/css/style.min.css', '../../resources/css/bt.min.css']
})
// declare var calculateAndDisplayRoute(directionsService, directionsDisplay) : any;
export class HomeComponent implements OnInit {
initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
var onChangeHandler = function() {
this.calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
}
calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: (<HTMLInputElement>document.getElementById('start')).value,
destination: (<HTMLInputElement>document.getElementById('end')).value,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
}
else {
window.alert('Directions request failed due to ' + status);
}
});
}
constructor() {
}
ngOnInit() {
this.initMap();
}
}
我不知道为什么会出现此错误消息。有人可以帮忙吗?
答案 0 :(得分:1)
显然,由于加载Google Maps JavaScript API时存在callback
参数而导致此错误:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
由于地图是通过ngOnInit
生命周期方法初始化的,因此回调参数可能会从url中丢弃。
Here is a demo演示了如何在Angular2 +应用程序中使用Google Maps Directions Service