在组件[Angular]中加载Google Maps JS API [英] Load Google Maps JS API in component [Angular]
本文介绍了在组件[Angular]中加载Google Maps JS API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从Angular组件中的网址加载外部 js
文件?
How is it possible to load an external js
file, from a url in an Angular component?
具体来说,我正在尝试将 google-maps-api
加载到我的角度项目中。目前,我在我的 index.html
中这样做:
To be specific, I'm trying to load google-maps-api
to my angular project. Currently, I'm doing it in my index.html
like this:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
注意:我知道 angular-maps
。这不是一个选项。
Note: I'm aware of angular-maps
. That's not an option.
推荐答案
一个解决方案是在 ngAfterViewInit()中动态创建脚本标签
import { DOCUMENT } from '@angular/common';
...
constructor(private @Inject(DOCUMENT) document,
private elementRef:ElementRef) {};
ngAfterViewInit() {
var s = this.document.createElement("script");
s.type = "text/javascript";
s.src = "https://maps.googleapis.com/maps/api/js?key=API_KEY";
this.elementRef.nativeElement.appendChild(s);
}
另见
https://github.com/angular/angular/issues/4903
更新
<div id="map" #mapRef></div>
export class GoogleComponent implements OnInit {
@ViewChild("mapRef") mapRef: ElementRef;
constructor() { }
ngOnInit() {
this.showMap();
}
showMap() {
console.log(this.mapRef.nativeElement);
const location = { lat: 28.5355, lng: 77.3910 };
var options = {
center: location,
zoom: 8
}
const map = new google.maps.Map(this.mapRef.nativeElement, options);
this.addMarket(map, location);
}
addMarket(pos, map) {
return new google.maps.Marker({
position: pos,
map: map,
});
}
}
这篇关于在组件[Angular]中加载Google Maps JS API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文