首页 > 解决方案 > 如何全局声明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"
  }
}

标签: javascriptnpmopenlayerspackage.jsonopenlayers-6

解决方案


在 map.js 中导出地图对象,然后在 analysis.js 中导入它:

地图.js

const map = new Map (...)

export default map

分析.js

import map from './map.js'
(...)
map.addLayer (vector);

推荐阅读