【发布时间】:2016-02-23 16:11:52
【问题描述】:
我有一个使用 openLayer3 的 Javascript 代码。我需要在 Typescript 中的 angular2 项目中实现此代码。
有人知道如何将openlayer与angular2 / Typescript一起使用吗?
非常感谢,
约翰
【问题讨论】:
标签: javascript angular typescript openlayers-3
我有一个使用 openLayer3 的 Javascript 代码。我需要在 Typescript 中的 angular2 项目中实现此代码。
有人知道如何将openlayer与angular2 / Typescript一起使用吗?
非常感谢,
约翰
【问题讨论】:
标签: javascript angular typescript openlayers-3
1.选项 A(使用 Angular CLI)
在您的 .angular-cli.json(位于您的项目根目录)中添加 Openlayers3:
...
"styles": [
"../node_modules/openlayers/dist/ol.css"
],
"scripts": [
"../node_modules/openlayers/dist/ol.js"
],
...
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);
}
}
【讨论】:
ReferenceError: ol is not defined。ol 的使用是否发生了变化?
至于你可能对 DefinitelyTyped 项目感兴趣的类型 - 你可以在那里找到 openlayers/openlayers.d.ts - 你可能需要了解 tsd、文件夹 convections 等。
至于 AngularJS 2,考虑到它仍处于测试阶段,经验告诉您主要靠自己。仍然谷歌搜索可以将您指向即https://gist.github.com/borchsenius/5a1ec0b48b283ba65021。
通常的做法是先根据已有的例子来了解AngularJS 2的方式。您应该很快就会注意到不同集成方式的许多常识。然后尝试以适当的方式调整您想要的内容。然后有很大一部分可以进一步提供和分享知识:)
同时了解现有的 AngularJS 1.x 解决方案(如 this article)可能会有所帮助。
【讨论】:
您可以使用 angular2-openlayers,可作为 npm 包或在此处使用:https://github.com/quentin-ol/angular2-openlayers
【讨论】:
src 的最后一次提交大约是 11 个月前。所以我不确定这是一个好的选择