我玩过angular2 maps ,但最后我想我想使用 google maps直接api。
将其加载到 Angular 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>
然后我在将保存 map 的组件的 ngAfterViewInit() Hook 内的组件中创建一个 map 。
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/core'导入{可注入(inject)};
@Injectable()
export class ScriptLoadService {
constructor() { }
public loadScript(url, id, c): void {
if (!document.getElementById(id)) {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.id = id;
if (c) {
script.addEventListener('load', function (e) {
c(null, e);
}, false);
}
document.head.appendChild(script);
}
}
}
googleMapURL: 'https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX&libraries=places'
ScriptLoadService 并在 ngOnInit 或 ngAfterViewInit 调用 loadScript
功能:
@ViewChild('mapElement') mapElm: ElementRef;//显示 map
constructor( private scriptLoadService: ScriptLoadService ) {} // inject the service
ngAfterViewInit() {
this.scriptLoadService.loadScript(environment.googleMapURL, 'google-map', () => {
this.center = new google.maps.LatLng(
this.lat,
this.lng);
// Create map
this.map = new google.maps.Map(this.mapElm.nativeElement, {
zoom: 18,
center: this.center,
disableDefaultUI: true,
scrollwheel: false,
});
// Add Marker to current location detected by browser
this.marker = new google.maps.Marker({
position: this.center,
map: this.map
});
});
}
希望这可以帮助 :)
关于angular - 将谷歌地图 api 加载到 angular2 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42893215/