Include JavaScript file inside TypeScript file

I’m working on Angular 2 and I’m trying to include inside a TypeScript (.ts file) a .js file. The JavaScript file I want to include is a simple google maps file, here it is:

<script>
var map;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8
    });
}
</script>

I downloaded the google-maps.d.ts declaration file from here and I moved this file in the same project (and folder) of my .ts file.

So I have a folder with the .ts, .js and google-maps.d.ts inside.

My .ts for completeness looks like:

import {Component, Injector, OnInit} from "angular2/core";
/// <reference path="./google-maps.d.ts" />

@Component({
    selector: 'my-map-selector',
    template: `
        <div id="map"></div>  // google map will appear here
    `,
})

export class mymapComponent {

}

Now, how do I import the .js file inside .ts?
I tried with /// <reference path="./google-maps.d.ts" /> but nothing happened (can’t see the map)

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

In fact a .d.ts file only describes the contract of the library but it’s not something usable for runtime.

If you want to use Google Maps, you could try the angular2-google-maps library and you need to configure it this way by adding the corresponding JS file:

<script src="node_modules/angular2-google-maps/bundles/ angular2-google-maps.js"></script>

See this question for more details:

Jason
Guest

To use javascript file in your typescript code, declare it’s source path in script tag, download it’s .d.ts file(if available), give its path in tsd.d.ts file . use ///reference to use that typing file.

If .d.ts file is not available, declare a variable for that library and use that variable for calling further function.

e.g. to use lodash.js code

1) declare it’s .js src path in script tag.

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.1/lodash.js"></script>

2) in .ts file, you can use it by declaring a variable. e.g.

declare var _:any;

See if it works

Regards

Ajay