Search code examples
openlayersturfjs

drawing openlayers 3 polygon with hole using turf


I am trying to draw a polygon (circle) with a hole (linear ring) using the DrawInteraction and turf, but instead of drawing what is expected and where it is expected, it is drawing a small circle at [0, 0]. see example That's not even adding the linear ring to the polygon -- it's the outer polygon that's drawing at [0, 0], linear ring is commented out at the moment.

    geometryFunction: function (coordinates, geometry) {
      if (!geometry) { geometry = new ol.geom.Polygon(null); }
      var center = coordinates[0];
      var last = coordinates[1];

      var radius = turf.distance(center, last, { units: 'degrees' });
      var outer = turf.circle(center, radius === 0 ? 0.00000001: radius, { units: 'degrees', steps: 100 });
      var inner = turf.circle(center, radius === 0 ? 0.000000005: radius, { units: 'degrees', steps: 20 });  
      geometry.setCoordinates([outer.geometry.coordinates[0]]);
 /* geometry.appendLinearRing([[outer.geometry.coordinates[0]]]);  */
      return geometry; 

}

I modified this example to ensure my coordinates generated by turf were ok.

Can anyone help me figure out what I'm doing wrong wrt to the Polygon & its Linear Ring?


Solution

  • You don't need Turf to do the job. I also didn't choose to use geometryFunction. I have only used drawend event

    drawInteraction.on('drawend', evt => {
      console.log(evt.feature);
    })
    

    I've made a complete sample to illustrate when you draw a circle, how to create a hole, forked from your sample