walkermatt / ol-layerswitcher

Layer control for OpenLayers
MIT License
387 stars 176 forks source link

Cannot read property 'dispatchEvent' of null when using renderpanel #422

Closed minorsecond closed 3 years ago

minorsecond commented 3 years ago

I'm trying to render the LS control in a div and am getting Cannot read property 'dispatchEvent' of null when attempting to do so. The full error reads:

ol-layerswitcher.js:317 Uncaught TypeError: Cannot read property 'dispatchEvent' of null
    at Function.renderPanel (ol-layerswitcher.js:317)
    at Object.parcelRequire.main.js.ol/ol.css (main.js:291)
    at newRequire (main.1f19ae8e.js:47)
    at main.1f19ae8e.js:81
    at main.1f19ae8e.js:120

The relevant JS code is:

const map = new Map({
    layers: [OSMLayer, vectorLayers],
    target: 'map',
    view: view,
});

const render_options = new RenderOptions({
    activationMode: 'mouseover',
    startActive: false,
    reverse: false,
    groupSelectStyle: "children"
});

LayerSwitcher.renderPanel(map, document.getElementById('ls_controller'), render_options);
map.addControl(layerSwitcher);

I suspect it has something to do with the options, but I haven't been able to find many examples as to how it should be structured. Am I doing this correctly?

walkermatt commented 3 years ago

Hi, dispatchEvent is called on the element panel argument passed to renderPanel. Can you check that document.getElementById('ls_controller') is returning an element.

minorsecond commented 3 years ago

Rookie mistake! I had to put it within window.onload = function () {}

Thank you for your help!