How to install Typescript typings for google maps

In practise, my use case is the Angular CLI, and there all I need is

npm install --save @types/google-maps

I tested these steps on my ionic 2 project and it is works perfectly:

  1. install typings globally :

npm install typings --global
  1. install google.maps via typings

typings install dt~google.maps --global --save
  1. open tsconfig.json and add "typings/*.d.ts" to your "include" array as shown below (tsconfig.json).

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5"
  },
  "include": [
    "src/**/*.ts",
    "typings/*.d.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

So what makes this exceptional is that the maps script needs to be downloaded separately from your app bundle. It's not your typical npm install where you get your .js and .ts nicely packaged for consumption.

TLDR: the typings can be installed via npm but the .js script must be downloaded via a <script> tag (for SPAs this tag can be appended to your web page on-the-fly to improve initial load time of your app, which is what I do).

My recommended path is as follows:

Install

npm install --save-dev @types/googlemaps

Import

import {} from 'googlemaps';

Load & Use (this function makes sure the maps script is only appended to the page once, so that it can be called over and over)

addMapsScript() {
  if (!document.querySelectorAll(`[src="${googleMapsUrl}"]`).length) { 
    document.body.appendChild(Object.assign(
      document.createElement('script'), {
        type: 'text/javascript',
        src: googleMapsUrl,
        onload: () => doMapInitLogic()
      }));
  } else {
    this.doMapInitLogic();
  }
}

Remember, the maps script must be appended to the page and the script must be downloaded before anything else happens. If you're using Angular, for example, I wrap the addMapsScript() logic in an observable and put in my map components route resolver.

Use the types (Type definitions include, but are not limited to):

const mapRef: google.maps.Map;
const bounds: google.maps.LatLngBounds;
const latLng: google.maps.LatLng;

Get Rid of the warning:@types/googlemaps/index.d.ts' is not a module.

Add a file at your projects root directory called index.d.ts and insert the following:

declare module 'googlemaps';


Update 01.06.2018 (findings of @DicBrus):

In order to import google namespaces and get rid of annoying error "Cannot find namespace 'google'" you should ensure that you've imported namespace definitions in @types/googlemaps

There are two ways to do it:

  1. triple-slash directive

    /// /node_modules/@types/googlemaps/index.d.ts" /> Worked fine, but not so elegant.

Documentation could be found here: https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html

  1. Ensure that it is imported in tsconfig.json and since it is imported you do not need to import something additionally

Detailed manual is here: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

you should check two subsections under compilerOptions: typeRoots and types

By default all type definitions under node_modules/@types are imported unless you specified exactly what you need.

In my particular case I had following section:

"types": []

It disables automatic inclusion of @types packages.

Removing this line re-solved issue for me, as well also adding triple-slash directive helped. But I chose the second solution.

As for the "empty" import, I didn't found any explanation how and why it works. I suppose that it does NOT import any module or class, but it does import namespaces. This solution is not suitable for me, since IDE marks this import as "not used" and it can be easily removed. E.g, webstorm's command Ctrl+Alt+O - prettifies code and removes all unnecessary imports.

Tags:

Typescript