2017-03-19 11 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()への呼び出しはgoogleが未定義で失敗します)。

私はnpm install --save @types/google-mapsでタイプをインストールしましたが、認識されているようです。

答えて

0

Getting startedを試してみましょう。このドキュメントでは、最初から始めて、angular2-google-mapsでAngular 2アプリを作成しましょう。それは、角度2を使用して統合されているので、よりクリーンでより効率的なGoogleマップのAPIをロードする方法です。

angular2とangular2-googleマップに慣れて、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/typescri[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を直接、特に非同期でロードし、スクリプトタグをインデックスに追加することはしませんでした。コンポーネント内のコードにスクリプトを追加するなど、いくつかのアプローチがありますが、ほとんどがちょっとハッキリしているようですので、角度2のこのapiを読み込む正しい方法は何かを尋ねています。 – nPn

関連する問題