【发布时间】:2017-08-11 02:50:04
【问题描述】:
我玩过angular2 maps,但最后我想我想直接使用google maps api。
将其加载到角度 2 中的最佳/正确方法是什么?目前我正在通过脚本标签加载它,插入到 index.html 文件中,就像这样。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ourlatitude</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
</head>
<body>
<script
src="https://maps.googleapis.com/maps/api/js?key=my_api_key">
</script>
<app-root>Loading...</app-root>
</body>
</html>
然后我在将保存地图的组件的 ngAfterViewInit() 挂钩内的组件中创建一个地图。
ngAfterViewInit() {
this.map = new google.maps.Map(this.mymap.nativeElement, {zoom: 4, center: {lat: -25.363, lng: 131.044} });
}
这似乎可行,但添加脚本标签似乎不是正确的做法。我尝试将脚本添加到 angular-cli.json 脚本:[] 数组,但这似乎不起作用(对 new google.maps.Map() 的调用失败,google 未定义)。
顺便说一句,我通过npm install --save @types/google-maps 安装了这些类型,它们似乎被识别了。
【问题讨论】:
-
这是一种方法,或者您可能想要使用专门为 Angular 编写的包装器。此外,当使用 vanilla lib 时,您应该在 NgZone 之外创建地图,以防止地图中的每个事件触发 Angular 应用程序中的更改检测。