0

Is there a way to enfore a just created Draw interaction to visualize itself before the first mousemouse event?

I use openlayers 4.6.5. The application creates an ol.interaction.Draw in response to a keyboard event. The type is a LineString. After the first mousemove the expected circle is shown at the mouse position. My problem is that the Draw interaction does not visualize anything until the first mouse move by the user.

1 Answers1

0

Interactions are driven by mouse events so you will need to re-run the last event.

Add a listener for pointermove events to your map and save the last one

var lastEvent;
map.on('pointermove', function(event){ lastEvent = event; });

then when you add the interaction get it to handle the last event

map.addInteraction(draw);
draw.handleEvent(lastEvent);

Version 4.6.4 works for me. An interaction is added by after 5 seconds, then removed and new interaction added at 5 and 10 seconds intervals:

  var raster = new ol.layer.Tile({
    source: new ol.source.OSM()
  });

  var source = new ol.source.Vector();

  var vector = new ol.layer.Vector({
    source: source
  });

  var map = new ol.Map({
    layers: [raster, vector],
    target: 'map',
    view: new ol.View({
      center: [-11000000, 4600000],
      zoom: 4
    })
  });

  var draw; // global so we can remove it later
  function addInteraction() {
      draw = new ol.interaction.Draw({
        source: source,
        type: 'LineString'
      });
      map.addInteraction(draw);
  }

  var lastEvent;
  map.on('pointermove', function(event){ lastEvent = event; });

  var add = false;
  setInterval(function(){
    add = !add;
    if (add) {
      addInteraction();
      draw.handleEvent(lastEvent);
    } else {
      map.removeInteraction(draw);
    }
  }, 5000);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.js"></script>
<div id="map" class="map"></div>
Mike
  • 16,042
  • 2
  • 14
  • 30
  • Thanks for the answer!! It tried that approach, but in version 4.6.4 Draw.handleEvent() is static. Passing the last pointermove event is giving an error. Should i move to the last 5.*.* version? – Arjan Lemmers Apr 07 '19 at 16:15
  • Thanks for the answer!! It is working for open-layers@4.6.4! In the typescript @types/openlayers@4.6.16 Draw.handleEvent() is defined static. I have worked around it. – Arjan Lemmers Apr 07 '19 at 17:27