angular & 将 openlayers 迁移到 ol & proj4js

angular & migration openlayers to ol & proj4js

尝试使用 openlayers 迁移基于 angular 的项目,远离已弃用的 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

在采用不同的方法两天后,尝试了这个和那个,意识到在这种特殊的库组合中,问题似乎是由于缺少新 ol 包的类型造成的。

我现在可以确认的 - 希望它能帮助其他人(我无法评论 yet) - is, that the support for proj4 is not yet existing in @types/ol:'4.6.2', but in @types/openlayers:'^4.6.12'

因此利用​​ proj4 为使用依赖项的 openlayers 提供不同的投影

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

将适用于以下代码片段,但 ol@types/ol 结合将不会:

进口

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' ],
    ...
]);

构造函数

ol.proj.setProj4(proj4);

试图完全避免@types/openlayers并求助于@types/ol,我最终想出了以下办法:

package.json

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

app/.../@types/ol/proj/proj4.d.ts(在应用程序文件夹下手动创建另一个类型文件)

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);

OpenLayers 5 不再有 setProj4 方法,取而代之的是 ol/proj/proj4 module. So, I followed the solution by @user10324080 and also discussion here 中的 register 方法,并采用 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"