Geographos
Geographos

Reputation: 1456

QGIS 2 web openlayers - TypeError: Cannot read properties of null

I would like to draw features in the OpenLayers map geerated by QGIS2web plugin. Since eveything seems to be alright and all the features come out now, unlike the recent situation.

My full code is here:

https://jsfiddle.net/go39r4j7/

but I am not convinced enough about the situation, as I keep getting the error:

TypeError: Cannot read properties of null (reading 'get')

enter image description here

which points out the following piece of code:

  map.forEachFeatureAtPixel(pixel, function(feature, layer) {
    if (feature instanceof ol.Feature && (layer.get("interactive") || layer.get("interactive") 
   == undefined)) {
        var doPopup = false;
        for (k in layer.get('fieldImages')) {
            if (layer.get('fieldImages')[k] != "Hidden") {
                doPopup = true;
              }
          }

Theoretically, I know, that I can't access the object, which is null:

https://idiallo.com/javascript/uncaught-typeerror-cannot-read-property-of-null

but any options I tried (removing this piece of code, removing the layer.get property, changing the layer.get("interactive") to my own id ("draw")) weren't successful.

Moroever this piece of code appears to be standard for similar situations like this:

https://gist.github.com/riccardoklinger/e3e2c512a366c8a6a296c10eef9c4162

How can I fix this issue? The tool works, although I am concerned about future modifications.

Upvotes: 0

Views: 2969

Answers (2)

andreaordonselli
andreaordonselli

Reputation: 139

I solved it in this way:

map.forEachFeatureAtPixel(pixel, function(feature, layer) {
            if (layer) { 
                var doPopup = false;
                for (k in layer.get('fieldImages')) {
                    if (layer.get('fieldImages')[k] != "Hidden") {
                        doPopup = true;
                    }
                }

Upvotes: 0

Mike
Mike

Reputation: 17907

https://openlayers.org/en/latest/apidoc/module-ol_Map-Map.html#forEachFeatureAtPixel

Feature callback. The callback will be called with two arguments. The first argument is one feature or render feature at the pixel, the second is the layer of the feature and will be null for unmanaged layers.

If you have an unmanaged layer (e.g. the overlay layer used by a Draw interaction) you will need to ensure you have a layer before using .get on it:

if (feature instanceof ol.Feature && layer && (layer.get("interactive") || layer.get("interactive") == undefined)) {

Upvotes: 1

Related Questions