javascript - Používanie openlayer3 v typescript/angular2
Mám Javascriptový kód, ktorý používa OpenLayer3. Potrebujem tento kód implementovať do projektu Angular2 v TypeScripte.
Niektorý vie, ako používať OpenLayer s Angular2/Typescript, prosím?
Ďakujem veľmi pekne,
Ján
Odpoveď č. 1
1. Možnosť A (Práca s Angular CLI)
Pridajte Openlayers3 do vášho .angular-cli.json (nachádzajúceho sa v koreňovom adresári vášho projektu):
...
"styles": [
"../node_modules/openlayers/dist/ol.css"
],
"scripts": [
"../node_modules/openlayers/dist/ol.js"
],
...
1. Možnosť B (Nepracuje sa s Angular CLI)
Pridajte Openlayers3 do svojho index.html („bežným“ spôsobom):
<script src="node_modules/openlayers/dist/ol.js"></script> <link rel="stylesheet" href="node_modules/openlayers/dist/ol.css">
2. Prístup k ol zo súboru TypeScript:
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);
}
}
Odpoveď č. 2
Čo sa týka typov, mohlo by vás zaujímať projekt DefinitelyTyped - tam nájdete openlayers/openlayers.d.ts - pravdepodobne budete potrebovať pochopiť tsd, konvencie priečinkov atď.
Pokiaľ ide o AngularJS 2, vzhľadom na to, že je stále v beta verzii, skúsenosti hovoria, že si väčšinou na svojom. Napriek tomu googlenie vám môže ukázať napríklad https://gist.github.com/borchsenius/5a1ec0b48b283ba65021.
Bežný prístup je najprv pochopiť spôsob AngularJS 2 podľa už existujúcich príkladov. Čoskoro by ste si mali všimnúť veľa zdravého rozumu v tom, ako vyzerajú rôzne integrácie. Potom sa skúste prispôsobiť tomu, čo chcete, vhodným spôsobom. Potom prichádza skvelá časť, dať ďalej a zdieľať vedomosti :)
Takisto môže pomôcť poznať existujúce riešenia AngularJS 1.x, ako je tento článok.
