新建了ionic项目,需要调用openlayers作为地图服务,由于openlayers没有@types(网上有,但不与openlayers最新版匹配),因此,写代码的时候没有智能提示,只能查看帮助写。
本文通过npm方式实现ionic或者angular加载openlayers。
1、安装ol模块
npm install ol
2、新建jsconfig.json(这一步貌似不需要也可以,但是是调用js的一个方法)
在项目根目录下新建jsconfig.json文件
在jsconfig.json中添加如下内容:
{
"compilerOptions": {
"checkJs": true,
// Point to the JSDoc typed sources when using modules from the ol package
"baseUrl": "./",
"paths": {
"ol": [
"node_modules/ol/src"
],
"ol/*": [
"node_modules/ol/src/*"
]
}
},
"include": [
"**/*.js",
"node_modules/ol/**/*.js"
]
}
jsconfig.json文件用于访问js文件,各参数设置参考相关内容(网络搜索jsconfig.json)。
3、添加css文件
在angular.json(angular项目为.angular-cli.json)文件中添加ol.css文件
"projects": {
"app": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
......
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
......
],
"styles": [
......
{
"input": "node_modules/ol/ol.css"
}
],
"scripts": []
},
4、代码编写
设置以上后,就可以写代码了。
import { Component } from '@angular/core';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
@Component({
selector: 'app-tab3',
templateUrl: 'tab3.page.html',
styleUrls: ['tab3.page.scss']
})
export class Tab3Page {
constructor() { }
ionViewDidEnter() {
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM()
})
],
view: new View({
center: [0, 0],
zoom: 0
})
});
}
}
效果如下图所示(我是在ionic中测试的):
ok,一切搞定,可以继续写代码了