John' John' - 1 year ago 90
TypeScript Question

Using openlayer3 in typescript/angular2

I have a Javascript code which use openLayer3. I need to implement this code in a angular2 project, in Typescript.

Someone knows how use openlayer with angular2 / Typescript please ?

Thanks a lot,


Answer Source

1. Option A (Working with the Angular CLI)

Add Openlayers3 in your .angular-cli.json (located at your project root):

"styles": [
"scripts": [

1. Option B (Not working with the Angular CLI)

Add Openlayers3 in your index.html (the "usual" way):

<script src="node_modules/openlayers/dist/ol.js"></script> <link rel="stylesheet" href="node_modules/openlayers/dist/ol.css">

2. Access ol from your typescript file:

import { AfterViewInit, Component, ElementRef, ViewChild } from "@angular/core";

// This is necessary to access ol3!
declare var ol: any;

    selector: 'my-app',
    template: `
    <h3> The map </h3>
    <div #mapElement id="map" class="map"> </div> 
    // The "#" (template reference variable) matters to access the map element with the ViewChild decorator!

export class AppComponent implements AfterViewInit {
    // This is necessary to access the html element to set the map target (after view init)!
    @ViewChild("mapElement") mapElement: ElementRef;

    public map: any;

        var osm_layer: any = new ol.layer.Tile({
            source: new ol.source.OSM()

        // note that the target cannot be set here! = new ol.Map({
            layers: [osm_layer],
            view: new ol.View({
            center: ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857'),
            zoom: 2

    // After view init the map target can be set!
    ngAfterViewInit() {;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download