Tips for declaring the OpenLayers map object globally

I have successfully created a map with ol 6 and added an OSM layer. Now I am trying to incorporate a vector layer that is coded in another JavaScript file, using the same 'map' object. Despite my efforts to declare it globally, it doesn't seem to be working. Here is my code:

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.

npm was used to install ol, and here is my package.json file:

{
  "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"
  }
}

Answer №1

To utilize the map object from your map.js file, you will need to export it and then import it into your analysis.js file:

map.js

const map = new Map (...)

export default map

analysis.js

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

Answer №2

I suggest coordinating the creation of the map in a centralized function like a "main

// map.js

import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import { Map, View } from 'ol';

// export as a "factory" function 
export const getMap = () => 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';

// export as a "factory" function 
export const getVectorLayer = () => 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'
        })
    })
});
// main.js

import { getMap } from 'map';
import { getVectorLayer } from 'analysis';

const map = getMap();
const vector = getVectorLayer();

map.addLayer(vector);

If you prefer not to do this, simply import the map into the analysis.js instead of main.js and call the function there.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulate the value of an HTML element's style parameter with jQuery

How do I change an element's style property using jQuery? This is the HTML code I am working with: <div id="template" style="width:200px; height:200px; border:none;">blabla...</div> I attempted to do this: $('#template').attr ...

Having difficulty formatting text alignment using CSS

Is there a way to maintain the alignment of text in the output of the 'About' section even when the content changes dynamically? I want the new line to appear just below 'Lorem', but currently, it shifts below the colon(:). Since the le ...

SimpleLightBox refuses to function

Having trouble getting SimpleLightBox to work properly? It seems like when you click on an image, it opens as a regular image on a blank page. I've added the JS and CSS files correctly (I double-checked in the source code) and included the HTML and JS ...

Commands for Yarn, such as type checking, testing, and formatting with Prettier, are encountering

I have been encountering errors in my Jenkins builds for the past 3 weeks. Despite numerous attempts, I cannot seem to get these commands to work within the Jenkins pipeline code using our shared libraries. The same commands work fine locally. The errors ...

Interactive Chart with Angular for Multiple Selections

I have a single page with a list menu By utilizing the list menu, I am able to generate various types of charts such as line chart, bar chart, pie chart, and more. However, I would like the previously selected charts, like the line chart, pie chart, etc. ...

I have been tirelessly attempting to resolve this issue, yet all my efforts have proven futile thus

Encountering an issue with web packs and nextjs. import NextDocument, { Html, Head, Main, NextScript } from 'next/document' import theme from '../libs/theme.js' export default class Document extends NextDocument { render() { retu ...

Ways to display map results in multiple columns utilizing react

I am facing a challenge and seeking guidance on how to achieve a specific layout using React. My goal is to display results in two columns as shown below: item 1 | item 4 item 2 | item 5 item 3 | item 6 I have attempted to check the array length and dete ...

I'm attempting to install all npm modules in the ../AppData/Roaming directory, but unfortunately, I keep encountering error code 4068 preventing it from being successful

When attempting to use the command "npm install -g" on Windows 8.1 with CMD running as administrator, I encountered the following error log: 0 info it worked if it ends with ok 1 verbose cli [ 'C:\Program Files\nodejs\\node.exe& ...

Error: Undefined variable in JavaScript obfuscation

My website has several small JavaScript files that I currently merge into one file and then minimize using terser. The website functions perfectly with the minimized version. Now, I want to take it a step further and obfuscate the code using JavaScript-Ob ...

Creating HighStock charts on the server-side using NodeJS

I'm currently utilizing HighStock to create charts within the browser. However, I now have a need to save some of these charts on the server. While I understand that HighCharts offers an export option to the server, I am interested in exploring other ...

Sending various types of data to an MVC C# controller using AJAX

Currently, I am utilizing AJAX to retrieve information from a Razor View and forward it to the controller. Although everything is functioning as expected, I now face the challenge of passing an array along with a string as the data: // View - JavaScript v ...

Unable to substitute a value using the useState hook in React

Whenever I click a key, I attempt to update the value of a variable but it appears not to be working as intended. ↓ The current implementation is not effective and needs improvement import React, { useState, useEffect } from 'react'; const Li ...

Finding a character that appears either once or thrice

In my work on JavaScript regex for markdown formatting, I am trying to match instances where a single underscore (_) or asterisk (*) occurs once (at the beginning, end, or surrounded by other characters or whitespace), as well as occurrences of three under ...

Methods for displaying data on the client side using express, MongoDB, and jade

I'm currently working on displaying data retrieved from my database using node.js, Express, and MongoDB. I successfully see the data in the console, but now I need to output it on the front-end using Jade. Here is the data I have retrieved: { date: ...

The dropdown menu in AngularJS is unable to retrieve the selected index

Presently, I have a dropdown menu: <select class="form-control" name="timeSlot" ng-model="user.dateTimeSlot" ng-change="dateTimeChanged(user.dateTimeSlot)" ng-blur="blur29=true" required style="float: none; margin: 0 auto;"> ...

Switching the background color of alternating divs in reverse order: a step-by-step guide

I am looking to alternate the background color of divs between odd and even, with the last div being grey and the second to last div being green. I have tried using the odd/even classes in CSS, but it did not work as expected. .main{ width:500px; height ...

The action of JQuery is modifying the value of the checkbox, but it is not visually showing as checked

I am working on a list that contains checkboxes and text, similar to an email inbox. My goal is to be able to check or uncheck the checkbox anytime I click anywhere on the list item (row). To achieve this functionality, I have used the following code withi ...

Is there a way to eliminate an object from a multidimensional nested array in JavaScript and retrieve the parent array?

Can anyone help me figure out how to delete the "fields" object with id 47 from this nested array using JavaScript and return the entire parent array? [{ "id": 10, "name": "phone", "fields": [ { ...

The carousel spun around, each section moving to the side on its own

One issue I'm facing is that on my page, I have multiple carousel rows. However, when I click on the "next" or "prev" button to navigate through the items in the carousel, it affects all carousels instead of just the one I clicked on. I've attem ...

Is it possible to observe the website functionalities and execute them directly from the console?

Question about JavaScript: Is it safe for a script tag to be visible in the body of the developer console and for functions to be run directly on the website? It raises security concerns, and there should be measures in place to prevent this kind of displa ...