google-maps - 从 Angular 2 服务设置谷歌地图 API key

标签 google-maps angular

我在 Angular 2 应用程序中使用 sebastine google map。我知道 AgmCoreModule.forRoot({ apiKey: "xxxxxxxx"}) 可用于设置 API key ,但我需要从我的 @component 中的 Angular 服务设置 API key 是否可能......需要帮助。

最佳答案

您可能需要更新提供一个像这样的自定义提供程序 { provide: MapsAPILoader, useClass: CustomLazyAPIKeyLoader } 在您导入 AgmCoreModule 的地方。

并在 CustomLazyAPIKeyLoader 类中覆盖加载方法。

import { Injectable, Inject } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { MapsAPILoader, LAZY_MAPS_API_CONFIG, LazyMapsAPILoaderConfigLiteral, GoogleMapsScriptProtocol } from 'angular2-google-maps/core';
import { DocumentRef, WindowRef } from 'angular2-google-maps/core/utils/browser-globals';

@Injectable()
export class CustomLazyAPIKeyLoader extends MapsAPILoader {
    private _scriptLoadingPromise: Promise<void>;
    private _config: LazyMapsAPILoaderConfigLiteral;
    private _windowRef: WindowRef;
    private _documentRef: DocumentRef;

    constructor( @Inject(LAZY_MAPS_API_CONFIG) config: any, w: WindowRef, d: DocumentRef, private http: Http) {
        super();
        this._config = config || {};
        this._windowRef = w;
        this._documentRef = d;
    }

    load(): Promise<void> {
        if (this._scriptLoadingPromise) {
            return this._scriptLoadingPromise;
        }

        const script = this._documentRef.getNativeDocument().createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.defer = true;
        const callbackName: string = `angular2GoogleMapsLazyMapsAPILoader`;

        this.http.get("getKey")
            .subscribe((res: any) => {
                this._config.apiKey = res._body;
                script.src = this._getScriptSrc(callbackName);
                this._documentRef.getNativeDocument().body.appendChild(script);
            });

        this._scriptLoadingPromise = new Promise<void>((resolve: Function, reject: Function) => {
            (<any>this._windowRef.getNativeWindow())[callbackName] = () => { console.log("loaded"); resolve(); };

            script.onerror = (error: Event) => { reject(error); };
        });

        
        return this._scriptLoadingPromise;
    }

    private _getScriptSrc(callbackName: string): string {
        let protocolType: GoogleMapsScriptProtocol =
            (this._config && this._config.protocol) || GoogleMapsScriptProtocol.HTTPS;
        let protocol: string;

        switch (protocolType) {
            case GoogleMapsScriptProtocol.AUTO:
                protocol = '';
                break;
            case GoogleMapsScriptProtocol.HTTP:
                protocol = 'http:';
                break;
            case GoogleMapsScriptProtocol.HTTPS:
                protocol = 'https:';
                break;
        }

        const hostAndPath: string = this._config.hostAndPath || 'maps.googleapis.com/maps/api/js';
        const queryParams: { [key: string]: string | Array<string> } = {
            v: this._config.apiVersion || '3',
            callback: callbackName,
            key: this._config.apiKey,
            client: this._config.clientId,
            channel: this._config.channel,
            libraries: this._config.libraries,
            region: this._config.region,
            language: this._config.language
        };
        const params: string =
            Object.keys(queryParams)
                .filter((k: string) => queryParams[k] != null)
                .filter((k: string) => {
                    // remove empty arrays
                    return !Array.isArray(queryParams[k]) ||
                        (Array.isArray(queryParams[k]) && queryParams[k].length > 0);
                })
                .map((k: string) => {
                    // join arrays as comma seperated strings
                    let i = queryParams[k];
                    if (Array.isArray(i)) {
                        return { key: k, value: i.join(',') };
                    }
                    return { key: k, value: queryParams[k] };
                })
                .map((entry: { key: string, value: string }) => { return `${entry.key}=${entry.value}`; })
                .join('&');
        return `${protocol}//${hostAndPath}?${params}`;
    }
}

 this.http.get("getKey")
            .subscribe((res: any) => {
                this._config.apiKey = res._body;
                script.src = this._getScriptSrc(callbackName);
                this._documentRef.getNativeDocument().body.appendChild(script);
            });

以上代码将使其异步。

关于google-maps - 从 Angular 2 服务设置谷歌地图 API key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42777296/

相关文章:

javascript - 在 Angular HttpClient 中实现接口(interface)有什么用?

forms - Angular 2 : How to get the selected value from different options of a form?

javascript - Angular 2 如何使基于父容器的 div 出现

angular - ng-bootstrap 和 Angular 5 兼容性

java - 使用 Android Studio 2.2.2 构建 Google map 示例项目

放大时Android MapView覆盖消失

C# Winform App - 显示 map

javascript - 带有 Jquery-ui slider 的 Angular2

javascript - 谷歌地图 "noClear"不工作

android - 创建一个链接,在任何设备上打开相应的 map 应用程序,并提供前往目的地的路线