在typescript/angular2中使用openlayer3

Joh*_*hn' 7 javascript typescript openlayers-3 angular

我有一个使用openLayer3的Javascript代码.我需要在Typescript中的angular2项目中实现此代码.

有人知道如何使用带有angular2/Typescript的openlayer吗?

非常感谢,

约翰

Lar*_*ars 8

1.选项A(使用Angular CLI)

.angular-cli.json(位于项目根目录)中添加Openlayers3 :

...
"styles": [
  "../node_modules/openlayers/dist/ol.css"
],
"scripts": [
  "../node_modules/openlayers/dist/ol.js"
],
...
Run Code Online (Sandbox Code Playgroud)

1.选项B(不使用Angular CLI)

index.html中添加Openlayers3 ("通常"方式):

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

2.从您的打字稿文件中访问ol:

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

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

@Component({
    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;

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

        // note that the target cannot be set here!
        this.map = 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() {
        this.map.setTarget(this.mapElement.nativeElement.id);
    }
}
Run Code Online (Sandbox Code Playgroud)