如何在 Angular 2 组件中集成 Google Maps API [英] How can I integrate Google Maps APIs inside an Angular 2 component
问题描述
我在文件 comp.ts 中定义了一个 Angular 2 组件,如下所示:
I have an Angular 2 component that is defined in the file comp.ts in this way like this:
import {Component} from 'angular2/core';
@component({
selector:'my-comp',
templateUrl:'comp.html'
})
export class MyComp{
constructor(){
}
}
因为我想让组件显示一个谷歌地图,所以我在文件 comp.html 中插入了以下代码:
Because I want the component to show a google map, I have inserted in the file comp.html the following code:
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
此代码已从此链接复制http://www.w3schools.com/googleAPI/google_maps_basic.asp一>.问题是该组件不显示地图.我做错了什么?
This code has been copied from this link http://www.w3schools.com/googleAPI/google_maps_basic.asp. The problem is that the component doesn't show the map. What have I done wrong?
推荐答案
我找到了解决方案.首先,下面这行:
I have found a solution. First of all, the following line:
<script src="http://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]"></script>
必须插入到 index.html 文件中.创建地图的代码必须插入到 comp.ts 文件中.特别是,它必须插入一个特殊的方法,即ngOnInit",它可以定位在类的构造函数之后.这是comp.ts:
must be inserted in the index.html file. The code which creates the map must be inserted in the comp.ts file. In particular, it must be inserted in a special method, namely "ngOnInit", which can be positioned after the constructor of the class. This is comp.ts:
import { Component } from 'angular2/core';
declare const google: any;
@Component({
selector: 'my-app',
templateUrl:'appHtml/app.html',
styleUrls: ['css/app.css']
})
export class AppMainComponent {
constructor() {}
ngOnInit() {
let mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
let map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
}
最后,id 为googleMap"的 div 将包含谷歌地图,必须插入到 comp.html 文件中,如下所示:
Finally, the div with id "googleMap", which is going to contain the google map, must be inserted in the comp.html file, which will look like this:
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
这篇关于如何在 Angular 2 组件中集成 Google Maps API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!