[GIS] Capture click while drawing a LineString in openlayers and query GeoServer WMS

asyncgeoservergetfeatureinfoopenlayerswms

While drawing a LineString in OpenLayers version 4.6.5, I would like to hook into the clicking of each point, and make an ajax call to a backend WMS service (geoserver).

If a Feature on the Tile layer is not clicked, reject the plotting of the point – like connect the dots of the features in the TILE layer.

I already have an asynchronous method that will retrieve the feature based on coordinates from the WMS service, returning a Promise of the Feature.

Here's some psuedo-code to explain what I want to do. I think it will be more difficult because it is asynchronous and requires a callback.

function onPointCreate(obj) {
  getFeatureFromWMS(obj.coordinate).then(
    function(feature) {
      if(feature) {
          // allow plotting of the point in the polyline
      } else {
          alert("Sorry, you must click on a feature");
          // don't allow plotting
      }
    });
}

I just can't find where to hook something like this up. I've tried geometryFunction and the drawstart event without success.

Best Answer

Doesn't seem that OpenLayers provide any event to handle the clicks while drawing, but it can be done.

The map 'click' event recives all the clicks made on the map, so the problem is to distinguish those clicks done while drawing a feature. This can be achieved with the 'drawstart' and 'drawend' events from the 'Draw' interaction object. You can set a boolean variable to true when 'drawstart' is called, and to false when 'drawend' is called. Then, on the map 'click' event, check this variable to know if the click was made while drawing, and then, if it is, test whether the click is valid or invalid. If the click is invalid, call the 'removeLastPoint' method from the 'Draw' interaction object.

Here is a working fiddle can try. It only allows drawing inside the green box:

https://jsfiddle.net/o2vehqk8/

EDIT. I've forgot the asynchronous part... You can still call the async method inside the click event, and call the 'removeLastPoint' when the async method returns that the coordinate is invalid. The problem will be when the wms service is slow, so it has to avoid the user to draw while the point isn't still validated.

Related Question