如何在Aurelia javascript应用程序中加载谷歌地图javascript api?

byc*_*kov 3 google-maps-api-3 node.js systemjs aurelia jspm

我找到了npm模块google-maps-api并安装了它(npm install google-maps-api)但是我无法弄清楚如何用systemjs/jspm导入它(jspm找不到这个模块).这是我的config.js的配置:

"paths": {
"*": "app/dist/*.js",
"github:*": "app/jspm_packages/github/*.js",
"npm:*": "app/jspm_packages/npm/*.js" }
Run Code Online (Sandbox Code Playgroud)

所以,当我尝试做这样的事情时:

import {mapsapi} from 'google-maps-api';
Run Code Online (Sandbox Code Playgroud)

我在浏览器控制台中收到以下错误:

GET https:// localhost:44308/app/dist/google-maps-api.js 404(未找到)

看看文件系统,我看到npm在app/node_modules/google-maps-api下安装了模块,那么如何在Aurelia模块的import子句中引用它呢?

byc*_*kov 6

我找到了一个解决方案并回答了我自己的问题:

我终于想到了如何用jspm安装它,所以你只需要给jspm提示一下从npm安装它就像这样:

jspm install npm:google-maps-api

在jspm完成安装后,import(no {} syntax)工作正常:

import mapsapi from 'google-maps-api';
Run Code Online (Sandbox Code Playgroud)

然后我在构造函数中注入它并实例化地理编码器api:

@inject(mapsapi('InsertYourGMAPIKeyHere'))
export class MyClass {         
    constructor(mapsapi) {
        let that = this;
        let maps = mapsapi.then( function(maps) {
            that.maps = maps;
            that.geocoder = new google.maps.Geocoder();
        });
...
}
Run Code Online (Sandbox Code Playgroud)

为了在div上创建地图,我使用EventAggregator订阅路由器:navigation:complete事件并使用setTimeout来安排地图创建:

        this.eventAggregator.subscribe('router:navigation:complete', function (e) {
        if (e.instruction.fragment === "/yourRouteHere") { 
            setTimeout(function() {
                that.map = new google.maps.Map(document.getElementById('map-div'),
                {
                    center: new google.maps.LatLng(38.8977, -77.0366),
                    zoom: 15
                });
            }, 200);
        }
    });
Run Code Online (Sandbox Code Playgroud)


jbx*_*jbx 6

这是一个完整的视图模型示例,用于attached()链接到您的视图.

import {inject} from 'aurelia-framework';
import mapsapi from 'google-maps-api';

@inject(mapsapi('your map key here'))

export class MapClass {

    constructor(mapsAPI) {

        this.mapLoadingPromise = mapsAPI.then(maps => {
            this.maps = maps;
        });
    }

    attached() {

        this.mapLoadingPromise.then(() => {

            var startCoords = {
                lat:  0,
                long: 0
            };

            new this.maps.Map(document.getElementById('map-div'), {
                center: new this.maps.LatLng(startCoords.lat, startCoords.long),
                zoom:   15
            });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)