2017-03-19 86 views
2

我玩过angular2 maps,但最终我想直接使用google maps api。将google maps api加载到angular2的最佳方式是什么?

什么是加载到角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()失败,谷歌未定义)。

顺便说一下,我通过npm install --save @types/google-maps安装了类型,他们似乎被认可。

回答

0

尝试使用Getting started,这个文件让我们从头开始,使用angular2-google-maps构建一个Angular 2应用程序。这是更加清洁和更有效的方式来加载谷歌地图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/[email protected]/dist/zone.js"></script> 
    <script src="https://unpkg.com/[email protected]/Reflect.js"></script> 
    <script src="https://unpkg.com/[email protected]/dist/system.js"></script> 
    <script src="https://unpkg.com/[email protected]/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 
--> 
+0

我其实知道如何使用angular2-google-maps。这是我目前使用的,但我有兴趣直接加载原始api,特别是异步,并且不添加脚本标记到我的索引。有几种方法,比如在组件内部的代码中添加脚本,但是大多数看起来有点冒险,所以我在问什么才是加载这个角度友好的api的正确方法。 – nPn

相关问题