【问题标题】:What's the best way to load the google maps api into angular2?将谷歌地图 api 加载到 angular2 的最佳方法是什么?
【发布时间】:2017-08-11 02:50:04
【问题描述】:

我玩过angular2 maps,但最后我想我想直接使用google maps api。

将其加载到角度 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>

然后我在将保存地图的组件的 ngAfterViewInit() 挂钩内的组件中创建一个地图。

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 编写的包装器。此外,当使用 vanilla lib 时,您应该在 NgZone 之外创建地图,以防止地图中的每个事件触发 Angular 应用程序中的更改检测。

标签: angular google-maps-api-3


【解决方案1】:

这就是我集成 google-maps 的方式:

  1. 我创建了脚本加载服务,它只在 需要 -

    从 '@angular/core' 导入 { Injectable };

    @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);
        }
      }
    
    }
    
  2. 在您的环境文件中添加您的 googleMapURL

谷歌地图网址: 'https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX&libraries=places'

  1. 现在您可以通过注入在任何组件中使用 google maps api ScriptLoadService 并在 ngOnInit 或 ngAfterViewInit 调用 loadScript 功能:

    @ViewChild('mapElement') mapElm: ElementRef; // 显示地图

    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
          });
    });
    }
    

希望这会有所帮助:)

【讨论】:

    【解决方案2】:

    尝试使用Getting started,此文档让您从头开始并使用 angular2-google-maps 构建 Angular 2 应用程序。加载 google maps api 的方式更简洁、更高效,因为它是使用 angular2 集成的。

    要熟悉 angular2 和 angular2-google-maps 并且不想使用 NPM 设置完整的项目,可以使用以下 Plunker。它具有使用 Angular2、Typescript 以及 angular2-google-maps 的所有依赖项:Plunkr link

    <!DOCTYPE html>
    <html>
      <head>
        <title>Angular 2 QuickStart</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    
        <script src="https://unpkg.com/zone.js@0.6.21/dist/zone.js"></script>
        <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
        <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
        <script src="https://unpkg.com/typescript@1.8.10/lib/typescript.js"></script>
        <script src="systemjs.config.js"></script>
    
        <script>
        System.import('app')
          .catch(console.error.bind(console));
      </script>
      </head>
    
      <!-- 3. Display the application -->
      <body>
        <my-app>Loading...</my-app>
    
      </body>
    
    </html>
    
    
    <!-- 
    Copyright 2016 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license
    -->
    

    【讨论】:

    • 我其实知道如何使用 angular2-google-maps。这是我目前正在使用的,但我有兴趣直接加载原始 api,特别是异步加载,而不向我的索引添加脚本标签。有几种方法,例如将脚本附加到组件内的代码中,但大多数看起来有点老套,所以我想知道加载这个对 angular 2 友好的 api 真正正确的方法是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多