从angular 2服务设置谷歌地图API密钥

时间:2017-03-14 03:31:19

标签: google-maps angular

我在角度2应用程序中使用sebastine谷歌地图。我知道AgmCoreModule.forRoot({apiKey:" xxxxxxxx"})可用于设置API密钥,但我需要在我的@component中从角度服务设置API密钥是否可能....需要帮助

3 个答案:

答案 0 :(得分:2)

您可能需要更新提供导入{ provide: MapsAPILoader, useClass: CustomLazyAPIKeyLoader }的{​​{1}}这样的自定义提供商。

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

上面的代码会使它异步。

答案 1 :(得分:0)

我添加了一个解析器以获取API密钥

import { Resolve, ActivatedRouteSnapshot } from '@angular/router'
import { Injectable, Inject } from '@angular/core'
import { SomeService } from '../services/some.service'
import { LazyMapsAPILoaderConfigLiteral, LAZY_MAPS_API_CONFIG } from '@agm/core'
import { Observable, of } from 'rxjs'
import { map, catchError } from 'rxjs/operators'

@Injectable()
export class GoogleMapAPiResolver implements Resolve<boolean> {
    constructor(
        private someService: SomeService,
        @Inject(LAZY_MAPS_API_CONFIG)
        private config: LazyMapsAPILoaderConfigLiteral
    ) {}

    resolve(router: ActivatedRouteSnapshot): Observable<boolean> {
        return this.someService.getGoogleMapApiKey().pipe(
            catchError(error => {
                return of(false)
            }),
            map(response => {
                this.config.apiKey = response
                return true
            })
        )
    }
}

SomeService使用一个返回密钥的端点

答案 2 :(得分:0)

您已将 API 密钥放在 awk -F ', ' ' NR == 1 {next} # skip 1st record 1st time FNR == NR { if (maxP < $2) # compute max(POP) maxP = $2 if (minD == "" || minD > $3) # compute min(dG) minD = $3 next } # print if 1st 2 lines OR "$2 >= .5 * max(POP) && $3 <= .5 * min(dG)" FNR <= 2 || ($2 >= (.5 * maxP) && $3 <= (.5 * minD)) ' file{,} 下的 app.module.ts 并确保在谷歌云控制台中启用 Maps JavaScript API https://console.cloud.google.com/apis/library/maps-backend.googleapis.com 谢谢! enter image description here

@NgModule