All files / src/app/map/drawing stripes-drawer.ts

13.58% Statements 11/81
21.43% Branches 3/14
25% Functions 1/4
13.04% Lines 9/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267              11x   11x             1x                                                                                 1x                                                                 1x                                                                               1x                                                                                                                                   1x                                                                                   1x                                                     1x  
import { loadModules } from 'esri-loader';
 
import { Drawer } from './drawer';
import { MapComponent } from '../map.component';
import { DrawActionEvent, getDefaultOutline, stripesWidth } from './utils';
import { Vector2d, clone, add, subtract, norm, normal, scalarMultiplication, vectorToArray } from '../../geometry/geometry2d';
 
export class StripesDrawer extends Drawer {
 
  private lastId = 0;
 
  /**
   * Draw stripes on a map.
   *
   * @param map The MapComponent on which the stripes must be drawn.
   */
  async draw(
    map: MapComponent
  ) {
    const [Draw] = await loadModules(['esri/views/2d/draw/Draw']);
 
    this.clearListeners();
 
    const draw: __esri.Draw = new Draw({
      view: map.mapView
    });
    const drawAction = draw.create('rectangle', {});
 
    this.drawActionListeners.push(
      drawAction.on(
        'vertex-add',
        async (event) => await this.createStripes(event, map)
      ),
 
      drawAction.on(
        'cursor-update',
        async (event) => await this.createStripes(event, map)
      ),
 
      drawAction.on(
        'draw-complete',
        async (event) => {
          await this.createStripes(event, map);
          this.currentGraphic = null;
          this.draw(map);
        }
      )
    );
  }
 
  /**
   * Generate stripes for given vertices captured by a DrawActionEvent and add them
   * to a MapComponent.
   *
   * @param event The DrawActionEvent which captured the vertices for which stripes must be generated.
   * @param map The MapComponent on which the stripes must be added.
   */
  private async createStripes(
    event: DrawActionEvent,
    map: MapComponent
  ) {
    if (this.currentGraphic != null) {
      map.drawingsLayer.remove(this.currentGraphic);
    }
 
    /* Only start drawing the passage when the user has clicked and is
       dragging the mouse. */
    if (event.vertices.length === 2) {
      const start: Vector2d = {x: event.vertices[0][0], y: event.vertices[0][1]};
      const end: Vector2d = {x: event.vertices[1][0], y: event.vertices[1][1]};
 
      if (event.type === 'draw-complete') {
        this.createFinalStripes(map, start, end);
 
      } else {
        this.currentGraphic = await this.createTemporaryStripes(map.mapView, start, end);
        map.drawingsLayer.add(this.currentGraphic);
      }
    }
  }
 
  /**
   * Create a temporary stripes rectanle to use while drawing or editing stripes on a map.
   *
   * @param mapView The Esri MapView on which the temporary stripes must be drawn.
   * @param start The coordinates of the starting point of the stripes rectangle.
   * @param end The coordinates of the ending point of the stripes rectangle.
   *
   * @returns A Graphic containing the temporary stripes rectangle to display.
   */
  async createTemporaryStripes(
    mapView: __esri.MapView,
    start: Vector2d,
    end: Vector2d
  ): Promise<__esri.Graphic> {
    const [
      Graphic,
      SimpleFillSymbol
    ] = await loadModules([
      'esri/Graphic',
      'esri/symbols/SimpleFillSymbol'
    ]);
 
    const rectangle = await this.createRectangle(mapView, start, end);
 
    const drawingSymbol: __esri.Symbol = new SimpleFillSymbol({
      color: [143, 143, 143, 0.75]
    });
    const outline: __esri.SimpleLineSymbol = await getDefaultOutline();
 
    const temporaryStripes = new Graphic({
      geometry: rectangle,
      symbol: drawingSymbol,
      visible: true,
      attributes: {
        temporaryStripes: true
      }
    });
    (temporaryStripes.symbol as __esri.FillSymbol).outline = outline;
 
    return temporaryStripes;
  }
 
  /**
   * Create the Graphics for a stripes drawing and add them to a map.
   *
   * @param map The MapComponent on which the stripes must be drawn.
   * @param start The coordinates of the starting point of the stripes on the map.
   * @param end The coordinates of the ending point of the stripes.
   */
  async createFinalStripes(
    map: MapComponent,
    start: Vector2d,
    end: Vector2d
  ) {
    const [
      Graphic,
      SimpleFillSymbol
    ] = await loadModules([
      'esri/Graphic',
      'esri/symbols/SimpleFillSymbol',
    ]);
 
    const line = subtract(start, end);
    const lineNorm = norm(line);
 
    // Set the number of stripes composing the drawing.
    let nbIters = Math.max(3, Math.floor(lineNorm / 2.5));
    nbIters = nbIters % 2 ? nbIters + 1 : nbIters;
    const jump = scalarMultiplication(line, 1 / nbIters);
 
    /* Create a graphic for each stripe and add it to the graphics layer.
       Stripes belonging to the same drawing will have the same id so they can
       be processed together when editing or deleting stripes. */
    let currentStart = clone(start);
    for (let i = 0; i < nbIters; i++) {
      const currentEnd = subtract(currentStart, jump);
 
      const rectangle = await this.createRectangle(map.mapView, currentStart, currentEnd);
 
      const currentSymbol = (i + 1) % 2 ?
        new SimpleFillSymbol({color: '#000000'}) :
        new SimpleFillSymbol({color: '#ffffff'});
 
      const startVector = i === 0 ? clone(currentStart) : null;
      const endVector = i === nbIters - 1 ? clone(currentEnd) : null;
 
      const stripe = new Graphic({
        geometry: rectangle,
        symbol: currentSymbol,
        visible: true,
        attributes: {
          id: this.lastId,
          stripes: true,
          start: startVector,
          end: endVector
        }
      });
 
      map.drawingsLayer.add(stripe);
      currentStart = clone(currentEnd);
    }
    this.lastId++;
  }
 
  /**
   * Create a rectangle geometry between a start and end point on an Esri MapView.
   *
   * @param mapView The MapView holding the spatial reference to which the
   * rectangle must be associated.
   * @param start The starting point of the rectangle.
   * @param end The ending point of the rectangle.
   *
   * @returns A new poylgon geometry with the shape of a rectangle between
   * the input start and end points.
   */
  private async createRectangle(
    mapView: __esri.MapView,
    start: Vector2d,
    end: Vector2d,
  ): Promise<__esri.Geometry> {
    const [Polygon] = await loadModules(['esri/geometry/Polygon']);
 
    // Line connecting the point clicked and the current position of the mouse.
    const line = subtract(start, end);
 
    // Normal vector to the line connecting the points.
    const lineNormal = scalarMultiplication(normal(line), stripesWidth);
 
    // Vertices of a rectangle between the two points.
    const vertices = [
      subtract(start, lineNormal),
      subtract(end, lineNormal),
      add(end, lineNormal),
      add(start, lineNormal)
    ];
 
    // Convert the vertices to arrays to pass them to the Polygon constructor.
    const verticesArray = vertices.map((vertex) => vectorToArray(vertex));
 
    const rectangle: __esri.Geometry = new Polygon({
      spatialReference: mapView.spatialReference.clone(),
      rings: verticesArray
    });
 
    return rectangle;
  }
 
  /**
   * Remove stripes from a map and return the coordinates of
   * its starting and ending points.
   *
   * @param map The MapComponent from which the stripes must be removed.
   * @param id The id of the stripes group which must be removed from the map
   *
   * @returns An array of 2 Vector2d instances containing the coordinates of the
   * starting and ending points of the deleted stripes.
   */
  deleteStripes(
    map: MapComponent,
    id: number
  ): Vector2d[] {
    let start: Vector2d = {x: 0, y: 0};
    let end: Vector2d = {x: 0, y: 0};
    const toRemove: __esri.Graphic[] = [];
 
    map.drawingsLayer.graphics.forEach(
      (graphic) => {
        if (graphic.attributes &&
            graphic.attributes.stripes &&
            graphic.attributes.id === id) {
          if (graphic.attributes.start) {
            start = graphic.attributes.start;
          } else if (graphic.attributes.end) {
            end = graphic.attributes.end;
          }
          toRemove.push(graphic);
        }
      }
    );
 
    // Only remove graphics after iterating over all of them.
    map.drawingsLayer.removeMany(toRemove);
    return [start, end];
  }
}