Search code examples
javascriptopenlayers

Openlayers can't draw the star


I have a set of options to draw, despite all working (as they belong to one code) I can't draw the star, which is to be incorporated from another solution.

I've picked it up from here:

https://openlayers.org/en/latest/examples/draw-shapes.html

and next modified it as per these approaches:

https://github.com/openlayers/openlayers/issues/8512

https://dolmenweb.it/viewers/openlayer/examples/draw-shapes.html

Now my code looks as you can see below:

var starInteraction = new ol.interaction.Draw({
 source: vectorLayer.getSource(),
 type: 'Polygon',
 geometryFunction: function (coordinates, geometry) {
 if (!geometry) {
  geometry = new ol.geom.Polygon([newCoordinates]);
 } else {
  geometry.setCoordinates([newCoordinates]);
 }
 var center = coordinates[0];
          var last = coordinates[1];
          var dx = center[0] - last[0];
          var dy = center[1] - last[1];
          var radius = Math.sqrt(dx * dx + dy * dy);
          var rotation = Math.atan2(dy, dx);
          var newCoordinates = [];
          var numPoints = 12;
          for (var i = 0; i < numPoints; ++i) {
            var angle = rotation + i * 2 * Math.PI / numPoints;
            var fraction = i % 2 === 0 ? 1 : 0.5;
            var offsetX = radius * fraction * Math.cos(angle);
            var offsetY = radius * fraction * Math.sin(angle);
            newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
          }
          newCoordinates.push(newCoordinates[0].slice());
          geometry.setCoordinates([newCoordinates]);
          return geometry;
        }
    }); 
    starInteraction.setActive(false);
    starInteraction.on('drawend', onDrawend);

Unfortunately, I am getting an error:

Uncaught TypeError: Cannot read properties of undefined

It refers mainly to this line of code:

   if (coordinates.length === 0) {

which exists in the other file. What might be missing here then? My full fiddle looks like this:

https://jsfiddle.net/Lb0xu8fe/


Solution

  • You have not defined newCoordinates when you call

     if (!geometry) {
      geometry = new ol.geom.Polygon([newCoordinates]);
     } 
    

    Either change that line to

     if (!geometry) {
      geometry = new ol.geom.Polygon([]);
     }
    

    so you have a empty array instead of an array with an undefined entry

    Alternatively you could move the line down as in the latest example https://openlayers.org/en/latest/examples/draw-shapes.html

     if (!geometry) {
      geometry = new ol.geom.Polygon([newCoordinates]);
     } else {
       geometry.setCoordinates([newCoordinates]);
     }