Search code examples
javascriptopenlayersopenlayers-3

Openlayers 3 : Interaction DragBox not working


I have a bug with OpenLayers v3 (no matter which version it is in V3). I try to add an ol.interaction.DragBox to my map, but when I start dragging, ol.js crashes with message :

ol.js:201 Uncaught TypeError: Cannot read property 'f' of null

at Array. (ol.js:201) at zm (ol.js:245) at bq (ol.js:370) at aq.ve (ol.js:371) at W.l.Kn (ol.js:453) at oi.f (ol.js:142)

This is when used with v3.9.0 Here is the code :

var vectorSource = new ol.source.Vector({
        url: 'https://openlayers.org/en/v4.1.0/examples/data/geojson/countries.geojson',
        format: new ol.format.GeoJSON()
      });

var map = new ol.Map({
   target: 'map',
   layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          }),
          new ol.layer.Vector({
            source: vectorSource
          })
   ],
   view: new ol.View({
     center: ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'),
     zoom: 4
   })
});

var dragBox = new ol.interaction.DragBox({
  condition: ol.events.condition.platformModifierKeyOnly
});

map.addInteraction(dragBox);

Here you can find a fiddle : http://jsfiddle.net/3svztkot/2/

Here you can find a fiddle with v4.1.0, with the exact same code, but here it is totally operational ! : http://jsfiddle.net/872cuk52/2/

Is there some known bug about this ? I searched for previous cases like mine, but didn't succeeded. Thanks for your help !


Solution

  • OK, I found the issue. Here is the "why" of the problem, maybe it will be useful for other people later.

    In Openlayers v3, you HAVE TO set a style in the interaction, like this :

    var dragBox = new ol.interaction.DragBox({
        condition: ol.events.condition.shiftKeyOnly,
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: [0, 0, 255, 1]
            })
        })
    });
    

    Then, it works. It seems that OpenLayers 4.1.0 at least defines a default style for the interaction, so it does not crash.