I have generated a map using ol 6. I have added an osm layer. Now I want to add a vector , which is coded in another javascript file. I want to use the same 'map' object . I tried to declare globally but its not working. My code is
map.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,
})
]
});
analysis.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.
I used npm to install ol. & my package.json is
{
"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"
}
}
I would recommend you to orchestrate the building of the map in something like a "main
If you don't want to do that, just import the map in the
analysis.js
instead ofmain.js
and call the function there.