javascript - 如何全局声明openlayers地图对象
问题描述
我使用 ol 6 生成了一个地图。我添加了一个 osm 层。现在我想添加一个向量,它被编码在另一个 javascript 文件中。我想使用相同的“地图”对象。我试图在全球范围内声明,但它不起作用。我的代码是
地图.js
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import {Map, View} from 'ol';
var map;
map = new Map({
target: 'map',
layers: [
new TileLayer({
title: 'OSM',
source: new OSM(),
opacity: 0.5,
})
]
});
分析.js
import {Vector as VectorSource} from 'ol/source';
import {Vector as VectorLayer} from 'ol/layer';
import Feature from 'ol/Feature';
var vector = new VectorLayer({
source: new VectorSource({
features: [new Feature({
geometry: new Point([571544.3902,1310700.2529]),
featureProjection: "EPSG:32643",
name: 'Somewhere near Nottingham',
})],
crossOrigin: "anonymous",
}),
style: new Style({
image: new Icon({
src: 'https://openlayers.org/en/latest/examples/data/icon.png'
})
})
})
map.addLayer(vector ); //this results in 'map' undefined error.
我使用 npm 安装 ol。&我的 package.json 是
{
"name": "gis",
"version": "1.0.0",
"description": "",
"main": "map*.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "parcel map.js",
"build": "parcel build --public-url . map*.js"
},
"author": "user123",
"license": "ISC",
"dependencies": {
"ol": "^6.4.3",
},
"devDependencies": {
"parcel-bundler": "^1.12.4"
}
}
解决方案
在 map.js 中导出地图对象,然后在 analysis.js 中导入它:
地图.js
const map = new Map (...)
export default map
分析.js
import map from './map.js'
(...)
map.addLayer (vector);
推荐阅读
- c# - 我使用的 HTTP 库与 Windows 7 不兼容吗?
- javascript - Await 给出错误“不能在异步函数之外使用关键字等待”
- c# - EPPlus - InsertColumn 函数无法正确复制样式
- sql - 如何将仪表板模板连接到 SQL 或任何其他数据库?
- node.js - 无法连接到 socketio/express 服务器
- javascript - 在数组中转换自定义 Json(对象)
- java - 在 Spring 中建立 OneToMany 关系后,我无法获取映射的对象
- iphone - 意外调用应用商店分发证书
- python - 使用 Python 的分发队列
- python - 如何使用 OAUTH/JWT 与 HANA 建立 Python 连接