将 Google 地图添加到 Angular CLI

4

我正在尝试将Google地图应用到我的angular-cli项目中。我知道有一个名为'angular2-google-maps'的组件(github),但我需要路由和更多自定义功能。

我发现了两种将地图应用到项目中的方法:

1: stackoverflow: 使用google api加载程序 - 但我不知道如何初始化google-maps......

2:使用一个DefinitelyTyped的google.maps.d.ts。 我通过--global(因为环境已过时...)将其安装到我的项目中,并添加了index.d.ts(全局)到src / typings.d.ts中,可以在.ts文件中使用“google.map..”:

  myLatLng = {lat: -25.363, lng: 131.044};
  map:any;

  constructor() {
    this.map = new google.maps.Map(document.getElementById('map'), {
      center: this.myLatLng,
      zoom: 4
    });
  }

但是如果我使用angular-cli构建它,就会出现错误: "ReferenceError: google未定义"。有什么想法吗?
1个回答

6

以下是将Google Maps组件添加到Angular CLI项目的详细步骤。

步骤1:从DefinitelyTyped安装google.maps:

typings i dt~google.maps --global --save

步骤二:如果您安装了较旧版本的typings,请添加以下内容。
/// <reference path="../typings/index.d.ts" />

步骤三:生成新的组件

将以下内容添加到您的src/typings.d.ts文件中

ng g component google-maps

请将以下代码添加到:
.ts文件中:
  height = '100px';
  myLatLng = {lat: -25.363, lng: 131.044};
  map:any;

  constructor(private googleApi:GoogleApiService) {}

  ngOnInit() {
    this.googleApi.initMap().then(() => {

      let latlng = new google.maps.LatLng(this.myLatLng.lat, this.myLatLng.lng);

      this.map = new google.maps.Map(document.getElementById('map'), {
        center: latlng,
        zoom: 4
      });

      new google.maps.Marker({
        position: latlng,
        map: this.map,
        title: 'Hello World!'
      });
    });
  }

.html :

<div id="map" [style.height]="height"></div>

第四步:生成新的服务

ng g service google-maps/shared/google-api

将GoogleApiService和HTTP_PROVIDERS添加到src/main.ts中。
代码:
const API_KEY = '[insert your code]';
const url = 'https://maps.googleapis.com/maps/api/js?key='+ API_KEY +'&callback=initMap';

@Injectable()
export class GoogleApiService {
  private loadMap: Promise<any>;

  constructor(private http:Http) {
    this.loadMap = new Promise((resolve) => {
      window['initMap'] = () => {
        resolve();
      };
      this.loadScript()
    });
  }

  public initMap():Promise<any> {
    return this.loadMap;
  }

  private loadScript() {
    let script = document.createElement('script');
    script.src = url;
    script.type = 'text/javascript';

    if (document.body.contains(script)) {
      return;
    }
    document.getElementsByTagName('head')[0].appendChild(script);
  }
}

也许你需要从spec.ts文件中删除一些行。 但是,您可以将GoogleMapsComponent添加为指令。

  • 使用路由等进行扩展非常容易。 也许如果我有时间,我会上传我的GoogleMapsComponent的当前版本到github。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接