bychkov bychkov - 5 months ago 266
Node.js Question

How to load google maps javascript api in Aurelia javascript application?

I found npm module google-maps-api and installed it (npm install google-maps-api) but I can't figure out how to import it with systemjs/jspm (jspm cannot find this module). Here's the configuration from my config.js:

"paths": {
"*": "app/dist/*.js",
"github:*": "app/jspm_packages/github/*.js",
"npm:*": "app/jspm_packages/npm/*.js" }


So, when I try do something like this:

import {mapsapi} from 'google-maps-api';


I get the following error in browser console:


GET https://localhost:44308/app/dist/google-maps-api.js 404 (Not Found)


Looking at the filesystem I see that npm installed the module under app/node_modules/google-maps-api so how do I reference it in the import clause from Aurelia module?

Answer

I found a solution and answering my own question here:

I finally figured how to install it with jspm, so you just need to give a hint to jspm to install it from npm like so:

jspm install npm:google-maps-api

After jspm completes installation, import (no {} syntax) works fine:

import mapsapi from 'google-maps-api';

then I inject it in constructor and instantiate geocoder 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();
        });
...
}

In order to create map on a div I use EventAggregator to subscribe for router:navigation:complete event and use setTimeout to schedule map creation:

        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);
        }
    });
Comments