4

Tried to migrate an angular-based project using openlayers away from deprecated openlayers-npm-package to recommended ol-npm-package. By debugging i realized that i had a problem with the previously still working integration of proj4.

After two days of following different approaches, trying this and that, realizing that in that special combination of libraries the problem seems to result from a lack of typings for the new ol-package.

What i now can confirm - and hope it helps others (i can't comment to SO-Answer yet) - is, that the support for proj4 is not yet existing in @types/ol:'4.6.2', but in @types/openlayers:'^4.6.12'.

So utilizing proj4 to provide different projections to openlayers using dependencies

"ol": "5.2.0",
"@types/openlayers": "4.6.12",

will work for the following code-snippet, but ol combined with @types/ol won't:

imports

import * as ol from 'openlayers';
import * as proj4x from 'proj4';
const proj4 = (proj4x as any).default;
proj4.defs([
  [ 'EPSG:25832', '+proj=utm +zone=32 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ],
    ...
]);

constructor

ol.proj.setProj4(proj4);
4

2 回答 2

3

试图完全避免 @types/openlayers 并诉诸 @types/ol 我最终想出了以下内容:

包.json

"dependencies": {
    ...
    "proj4": "2.4.4",
    ...

app/.../@types/ol/proj/proj4.d.ts(在 app-folder 下手动创建了另一个类型文件)

export namespace ol {
    namespace proj {
        function setProj4(proj4: any): void;
    }
}

在例如中导入和定义。一个组件

import proj from 'ol/proj';
import * as proj4x from 'proj4';
const proj4 = (proj4x as any).default;
// Two example-projections (2nd is included anyway)
proj4.defs([
    [ 'EPSG:25832', '+proj=utm +zone=32 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ],
    [ 'EPSG:4326',  '+proj=longlat +datum=WGS84 +no_defs' ]
]);

在构造函数中- 最后用 ol 注册 proj4

proj.setProj4(proj4);
于 2018-09-13T07:37:03.307 回答
1

OpenLayers 5 不再有 setProj4 方法,而是ol/proj/proj4模块中的 register 方法。因此,我遵循@user10324080 的解决方案并在此处进行了讨论,并得出了使用 Angular 6 的以下解决方案:

  1. 将以下行添加到 tsconfig.js 文件中 CompilerOptions 的末尾:

    "allowSyntheticDefaultImports": true, "esModuleInterop":true

  2. 我创建了文件@types/ol/proj/proj4.d.ts并在其中添加:

    export function register(proj4: any): void;

  3. 在创建地图的 .ts 文件中,我添加了:

    import { fromLonLat } from 'ol/proj.js' import {register as proj4register } from 'ol/proj/proj4' import proj4 from 'proj4'; proj4.defs([[ 'EPSG:3067', '+proj=utm +zone=35 +ellps=GRS80 +units=m +no_defs']]); // Constuctor: proj4register(proj4); // ngOnInit: var view = new View({ projection: 'EPSG:3067', center: fromLonLat([27.47, 64.88], 'EPSG:3067'), zoom: 5 });

我已经安装了以下版本的库和类型定义:

"ol": "^5.2.0",
"proj4": "^2.5.0",
"@types/ol": "^4.6.2",
"@types/proj4": "^2.3.4"
于 2018-09-23T11:55:30.350 回答