如何在Angular 2组件中集成Google Maps API

nix*_*x86 20 google-maps angular2-template angular

我有一个Angular 2组件,在文件comp.ts中以这种方式定义,如下所示:

import {Component} from 'angular2/core';

@component({
    selector:'my-comp',
    templateUrl:'comp.html'
})

export class MyComp{
    constructor(){
    }
}
Run Code Online (Sandbox Code Playgroud)

因为我希望组件显示谷歌地图,我已在comp.html文件中插入以下代码:

<!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> 
Run Code Online (Sandbox Code Playgroud)

此代码已从此链接http://www.w3schools.com/googleAPI/google_maps_basic.asp中复制.问题是组件不显示地图.我做错了什么?

小智 23

是的,你可以这样做.但是在typescript编译器中会出现错误,所以不要忘记隐式声明google变量.

declare var google: any;
Run Code Online (Sandbox Code Playgroud)

在组件导入后立即添加此指令.

import { Component, OnInit } from '@angular/core';
declare var google: any;

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent implements OnInit {
  ngOnInit() {
    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("gmap"), mapProp);
  }
}
Run Code Online (Sandbox Code Playgroud)


nix*_*x86 17

我找到了解决方案.首先,以下行:

<script src="http://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]"></script>
Run Code Online (Sandbox Code Playgroud)

必须插入index.html文件中.必须将创建映射的代码插入comp.ts文件中.特别是,它必须插入一个特殊的方法,即"ngOnInit",它可以放在类的构造函数之后.这是compts:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,必须在comp.html文件中插入ID为"googleMap"的div,它将包含google地图,如下所示:

<body>
    <div id="googleMap" style="width:500px;height:380px;"></div>
</body>
Run Code Online (Sandbox Code Playgroud)

  • @tkhm 我在控制台中收到 `google is not defined` (2认同)