DynamicLabel.js 16.8 KB
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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
/**
 * Created by Nicholas Hallahan <nhallahan@spatialdev.com>
 *       on 7/11/14.
 */
function Feature(label, pbfFeature, options) {
  this.dynamicLabel = label;
  this.mvtFeature = pbfFeature;
  this.mvtLayer = pbfFeature.mvtLayer;
  this.mvtSource = pbfFeature.mvtLayer.mvtSource;
  this.map = label.map;
  this.activeTiles = label.activeTiles;
  this.marker = null;

  this.tilePoints = {};
  this.tileLines = {};
  this.tilePolys = {};

  // default options
  this.options = {};

  // apply options
  for (var key in options) {
    this.options[key] = options[key];
  }

  // override the style function if specified
  if (pbfFeature.style.dynamicLabel) {
    this._styleFn = pbfFeature.style.dynamicLabel;
  }

  this.style = this._styleFn();
  this.icon = L.divIcon({
    className: this.style.cssClass || 'dynamicLabel-icon-text',
    html: this.style.html || 'No Label',
    iconSize: this.style.iconSize || [50,50]
  });
}

Feature.prototype.addTilePolys = function(ctx, polys) {
  this.tilePolys[ctx.id] = polys;
  this.computeLabelPosition();
};

Feature.prototype.computeLabelPosition = function() {
  var activeTiles = this.activeTiles;
  var tilePolys = {};
  // only passing over tiles currently on the screen
  for (var id in activeTiles) {
    var t = this.tilePolys[id];
    if (t) tilePolys[id] = t;
  }
  var dynamicLabel = this.dynamicLabel;
  var job = {
    extent: this.mvtFeature.extent,
    tileSize: this.mvtFeature.tileSize,
    tilePolys: tilePolys
  };
  var feature = this;
  this.dynamicLabel.submitPositionJob(job, function(evt) {
    var data = evt.data;
    console.log([data.status, data]);
    if (data.status !== 'WARN') {
      // returns worker to the pool
      dynamicLabel.freePositionWorker(this);
    }

    if (data.status === 'OK' && map.getZoom() === data.z) {
      var pt = L.point(data.x, data.y);
      positionMarker(feature, pt);
    }

    if (data.status === 'WARN' && data.tile === '5:18:16') {
      var cEdgeGeoJson = unprojectGeoJson(feature.map, data.cEdgePolys);
      var nEdgeGeoJson = unprojectGeoJson(feature.map, data.nEdgePolys);

      L.geoJson(cEdgeGeoJson, {
        style: {
          color: "#ff7800",
          weight: 3,
          opacity: 0.4,
          fill: false
        }
      }).addTo(feature.map);

      L.geoJson(nEdgeGeoJson, {
        style: {
          color: "green",
          weight: 1,
          opacity: 0.7,
          fill: false
        }
      }).addTo(feature.map);
    }
  });
};

function positionMarker(feature, pt) {
  var map = feature.map;
  var latLng = map.unproject(pt);
  if (!feature.marker) {
    feature.marker = L.marker(latLng, {icon: feature.icon});
    feature.marker.addTo(map);
  } else {
    feature.marker.setLatLng(latLng);
  }
//  L.marker(latLng).addTo(map);
}

/**
 * This is the default style function. This is overridden
 * if there is a style.dynamicLabel function in MVTFeature.
 */
Feature.prototype._styleFn = function() {

};

/**
 * Converts projected GeoJSON back into WGS84 GeoJSON.
 * @param geojson
 * @returns {*}
 */
function unprojectGeoJson(map, geojson) {
  var wgs84Coordinates = [];
  var wgs84GeoJson = {
    type: 'MultiPolygon',
    coordinates: wgs84Coordinates
  };
  var coords = geojson.coordinates;
  for (var i = 0, len = coords.length; i < len; i++) {
    var innerCoords = coords[i];
    wgs84Coordinates[i] = [];
    for (var j = 0, len2 = innerCoords.length; j < len2; j++) {
      var innerCoords2 = innerCoords[j];
      wgs84Coordinates[i][j] = [];
      for (var k = 0, len3 = innerCoords2.length; k < len3; k++) {
        var coord = innerCoords2[k];
        var latlng = map.unproject(L.point(coord));
        wgs84Coordinates[i][j][k] = [latlng.lng, latlng.lat];
      }
    }
  }
  return wgs84GeoJson;
}


var reader = new jsts.io.GeoJSONReader();
var parser = new jsts.io.GeoJSONParser();

onmessage = function(evt) {
  var msg = evt.data;
  for (var key in msg) {
    var fn = calcPos[key];
    if (typeof fn === 'function') fn(msg);
  }
};

/**
 * Computes the position for a dynamicLabel depending on
 * the data type...
 */
calcPos = {
  tilePoints: function(msg) { /* TODO */ },
  tileLines: function(msg)  { /* TODO */ },

  tilePolys: function(msg) {
    var tilePolys = msg.tilePolys;
    var tileCls = classifyAndProjectTiles(tilePolys, msg.extent, msg.tileSize);
    var largestPoly = mergeAndFindLargestPolygon(tilePolys, tileCls);
    // if there are no polygons in the tiles, we dont have a center
    if (!largestPoly.tid) {
      postMessage({status: 'NO_POLY_IN_TILES'});
    } else {
      var center = centroid(tilePolys[largestPoly.tid][largestPoly.idx]);
      if (!center || !center.x || !center.y) {
        center = {
          status: 'ERR',
          description: 'No centroid calculated.'
        }
      } else {
        center.status = 'OK';
        center.z = parseInt(largestPoly.tid.split(':')[0]);
      }
      postMessage(center);
    }
  }
};

/**
 * Goes through each tile and and classifies the paths...
 *
 * @param tiles
 * @param extent
 */
function classifyAndProjectTiles(tilePaths, extent, tileSize) {
  var tileCls = {};
  for (var id in tilePaths) {
    var t = tilePaths[id];
    var cls = classifyAndProject(t, extent, tileSize, id);
    tileCls[id] = cls;
  }
  return tileCls;
}

/**
 * Checks through the coordinate arrays and classifies if they
 * leave the bounds of the extent and where.
 *
 * @param coordsArray
 */
function classifyAndProject(coordsArray, extent, tileSize, id) {
  // we need to know the tile address to project the coords
  var zxy = id.split(':');
  var x = parseInt(zxy[1]);
  var y = parseInt(zxy[2]);

  // the classification the the coords (what tile the intersect with)
  var cls = {
    internal: [],
    topLeft: [],
    left: [],
    bottomLeft: [],
    bottom: [],
    bottomRight: [],
    right: [],
    topRight: [],
    top: []
  };

  for (var i = 0, len = coordsArray.length; i < len; i++) {
    var coords = coordsArray[i];
    var overlapNeighbors = {};
    var pathInExtentAtLeastOnce = false;

    for (var j = 0, len2 = coords.length; j < len2; j++) {
      var coord = coords[j];
      var neighbor = checkCoordExtent(coord, extent);

      // project the coord to the pixel space of the world (Spherical Mercator for Zoom Level)
      coords[j] = project(coord, x, y, extent, tileSize);

      // coord is outside tile
      if (neighbor) {
        overlapNeighbors[neighbor] = true;
      }
      // coord is inside tile
      else {
        pathInExtentAtLeastOnce = true;
      }
    }

    // path is entirely inside of tile
    if (Object.keys(overlapNeighbors).length === 0) {
      cls.internal.push(i);
    }
    // path leaves the tile
    else {
      for (var neighbor in overlapNeighbors) {
        // We don't want paths that are never in the extent at all...
        if (pathInExtentAtLeastOnce) {
          cls[neighbor].push(i);
        }
      }
    }
  }
  return cls;
}

/**
 * Checks to see if the path has left the extent of the vector tile.
 * If so, we need to continue creating the polygon with coordinates
 * from a neighboring tile...
 *
 * @param pbfFeature
 * @param ctx
 * @param coords
 */
function checkCoordExtent(coord, extent) {
  var x = coord.x;
  var y = coord.y;

  // outside left side
  if (x < 0) {
    // in top left tile
    if (y < 0) {
      return 'topLeft';
    }
    // in bottom left tile
    if (y > extent) {
      return 'bottomLeft';
    }
    // in left tile
    return 'left';
  }

  // outside right side
  if (x > extent) {
    // in top right tile
    if (y < 0) {
      return 'topRight';
    }
    // in bottom right tile
    if (y > extent) {
      return 'bottomRight';
    }
    // in right tile
    return 'right';
  }

  // outside top side
  if (y < 0) {
    return 'top';
  }

  // outside bottom side
  if (y > extent) {
    return 'bottom';
  }

  return null;
}

var neighborFns = {
  top: function(id) {
    var zxy = id.split(':');
    return zxy[0] + ':' + zxy[1] + ':' + (parseInt(zxy[2]) - 1);
  },
  topLeft: function(id) {
    var zxy = id.split(':');
    return zxy[0] + ':' + (parseInt(zxy[1]) - 1) + ':' + (parseInt(zxy[2]) - 1);
  },
  left: function(id) {
    var zxy = id.split(':');
    return zxy[0] + ':' + (parseInt(zxy[1]) - 1) + ':' + zxy[2];
  },
  bottomLeft: function(id) {
    var zxy = id.split(':');
    return zxy[0] + ':' + (parseInt(zxy[1]) - 1) + ':' + (parseInt(zxy[2]) + 1);
  },
  bottom: function(id) {
    var zxy = id.split(':');
    return zxy[0] + ':' + zxy[1] + ':' + (parseInt(zxy[2]) + 1);
  },
  bottomRight: function(id) {
    var zxy = id.split(':');
    return zxy[0] + ':' + (parseInt(zxy[1]) + 1) + ':' + (parseInt(zxy[2]) + 1);
  },
  right: function(id) {
    var zxy = id.split(':');
    return zxy[0] + ':' + (parseInt(zxy[1]) + 1) + ':' + zxy[2];
  },
  topRight: function(id) {
    var zxy = id.split(':');
    return zxy[0] + ':' + (parseInt(zxy[1]) + 1) + ':' + (parseInt(zxy[2]) - 1);
  }
};

/**
 * Projects a vector tile point to the Spherical Mercator pixel space for a given zoom level.
 *
 * @param vecPt
 * @param tileX
 * @param tileY
 * @param extent
 * @param tileSize
 */
function project(vecPt, tileX, tileY, extent, tileSize) {
  var div = extent / tileSize;
  var xOffset = tileX * tileSize;
  var yOffset = tileY * tileSize;
  return {
    x: Math.floor(vecPt.x / div + xOffset),
    y: Math.floor(vecPt.y / div + yOffset)
  };
}

var inverseSides = {
  top: 'bottom',
  topLeft: 'bottomRight',
  left: 'right',
  bottomLeft: 'topRight',
  bottom: 'top',
  bottomRight: 'topLeft',
  right: 'left',
  topRight: 'bottomLeft'
};

function mergeAndFindLargestPolygon(tilePolys, tileCls) {
  var largestPoly = {
    tid: null, // tile id to get the tile in tilePolys
    idx: null, // index of array of polys in tile
    area: null // area of the poly
  };
  for (var id in tileCls) {
    var cCls = tileCls[id];     // center tile classifications
    var cPolys = tilePolys[id]; // center tile polygons

    // Polygons internal to a tile do not need to be merged, but they may be the largest...
    var internalClsArr = cCls.internal;
    if (typeof internalClsArr === 'array') {
      for (var i = 0, len = internalClsArr.length; i < len; i++) {
        findLargestPoly(largestPoly, tilePolys, id, internalClsArr[i]);
      }
    }

    for (var edge in neighborFns) {
      var cClsEdgeArr = cCls[edge]; // poly idxs for center edge classification
      // continue if there are no overlapping polys on a given edge...
      if (cClsEdgeArr.length === 0) {
        continue;
      }
      var nId = neighborFns[edge](id); // neighboring tile id
      var nCls = tileCls[nId];         // neighboring tile classifications
      var nPolys = tilePolys[nId];     // neighboring tile polygons

      for (var j = 0, len2 = cClsEdgeArr.length; j < len2; j++) {
        var cPolyIdx = cClsEdgeArr[j]; // a given center poly idx that overlaps the edge we are examining

        // If we have a neighboring tile, we get the overlapping polygons that correspond with the center tile.
        // We then try to union the polygons...
        if (nCls) {
          var inv = inverseSides[edge];

          // We are just going to do 1 poly from center tile at a time so we can keep track of the one we are actually doing the merge on...
          var cEdgePolys = polygonSetToGeoJson(cPolys, [cPolyIdx]); // 1 poly
          var nEdgePolys = polygonSetToGeoJson(nPolys, nCls[inv]);  // 1 or more polys

          var ctrJsts = reader.read(cEdgePolys);
          var nbrJsts = reader.read(nEdgePolys);

          if (id === '5:18:16') {
            console.log('b');
          }
          try {
            // https://www.youtube.com/watch?v=RdSmokR0Enk
            var union = ctrJsts.union(nbrJsts);

            // the new merged polygon
            var unionPoly = union.shell.points;

            // Neighboring tile's inverse edge should be empty,
            // because the corresponding shape has been merged.
            nCls[inv] = [];

            // Replace the polygon in the center tile with the new merged polygon
            // so other tiles can merge this if needed.
            cPolys[cPolyIdx] = unionPoly;

          } catch (e) {
            //NH TODO: WHY?
            postMessage({
              status: 'WARN',
              details: 'union failed',
              ctrJsts:ctrJsts,
              nbrJsts:nbrJsts,
              cEdgePolys:cEdgePolys,
              nEdgePolys:nEdgePolys,
              e:e,
              tile: id
            });
          }
        }

        // Regardless of whether we unioned or not, we want to check to see if this polygon is the largest...
        findLargestPoly(largestPoly, tilePolys, id, cPolyIdx);
      }

    }
  }
  return largestPoly;
}

/**
 * Converts the array of arrays of {x,y} points to GeoJSON.
 *
 * Note that the GeoJSON we are using is in the projected pixel
 * space. Normally GeoJSON is WGS84, but we don't care, because
 * we are just doing a union topology check.
 *
 * @param polys
 * @returns {{type: string, coordinates: Array}}
 */
function polygonSetToGeoJson(polys, idxArr) {
  var coordinates = [];
  var geojson = {
    type: 'MultiPolygon',
    coordinates: coordinates
  };
  for (var i = 0, len = idxArr.length; i < len; i++) {
    var idx = idxArr[i];
    var poly = polys[idx];
    var geoPoly = [];
    for (var j = 0, len2 = poly.length; j < len2; j++) {
      var pt = poly[j];
      var geoPt = [pt.x, pt.y];
      geoPoly.push(geoPt);
    }
    geoPoly = [geoPoly]; // its an array in array, other items in the array would be rings
    coordinates.push(geoPoly);
  }
  return geojson;
}


//  http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon

function area(poly) {
  var area = 0;
  var len = poly.length;
  for (var i = 0, j = len - 1; i < len; j=i, i++) {
    var p1 = poly[j];
    var p2 = poly[i];

    area += p1.x * p2.y - p2.x * p1.y;
  }

  return Math.abs(area / 2);
}

/*
 NH TODO: We are indeed getting the centroid, but ideally we
 want to check if the centroid is actually within the polygon
 for the polygons that bend like a boomarang. If it is outside,
 we need to nudge it over until it is inside...
 */
function centroid(poly) {
  var len = poly.length;
  var x = 0;
  var y = 0;
  for (var i = 0, j = len - 1; i < len; j=i, i++) {
    var p1 = poly[j];
    var p2 = poly[i];
    var f = p1.x * p2.y - p2.x * p1.y;
    x += (p1.x + p2.x) * f;
    y += (p1.y + p2.y) * f;
  }
  f = area(poly) * 6;

  return {
    x: Math.abs(x/f),
    y: Math.abs(y/f)
  };
}

function findLargestPoly(largestPoly, tilePolys, tid, idx) {
  if (!largestPoly.tid) {
    largestPoly.tid = tid;
    largestPoly.idx = idx;
    largestPoly.area = area(tilePolys[tid][idx]);
    return largestPoly;
  }
  var largestArea = largestPoly.area;
  var polyArea = area(tilePolys[tid][idx]);

  if (polyArea > largestArea) {
    largestPoly.tid = tid;
    largestPoly.idx = idx;
    largestPoly.area = polyArea;
  }

  return largestPoly;
}

/**
 * There should be one instance of Label per MVTSource.
 *
 * @param map
 * @param options
 * @constructor
 */
function DynamicLabel(map, pbfSource, options) {
  this.map = map;
  this.mvtSource = pbfSource;

  // default options
  this.options = {
    numPosWorkers: 8
  };

  // apply options
  for (var key in options) {
    this.options[key] = options[key];
  }

  this.positionWorkerPool = [];
  this.positionWorkerQueue = [];

  for (var wkr = 0; wkr < this.options.numPosWorkers; wkr++) {
    this.positionWorkerPool.push( new Worker(POS_WKR_LOC) );
  }

  /**
   * A hash containing keys to all of the tiles
   * currently in the view port.
   */
  this.activeTiles = {};

  this._determineActiveTiles();
  var self = this;
  this.map.on('move', function() {
    self._determineActiveTiles();
  });

}


/**
 * FACTORY METHODS
 */

DynamicLabel.prototype.createFeature = function(pbfFeature, options) {
  return new Feature(this, pbfFeature, options);
};



/**
 * PRIVATE METHODS
 * @private
 */

DynamicLabel.prototype._determineActiveTiles = function() {
  var activeTiles = this.activeTiles = {};
  var bounds = this.map.getPixelBounds();
  var tileSize = this.mvtSource.options.tileSize;
  var z = this.map.getZoom();

  var minX = Math.floor(bounds.min.x / tileSize);
  var minY = Math.floor(bounds.min.y / tileSize);
  var maxX = Math.floor(bounds.max.x / tileSize);
  var maxY = Math.floor(bounds.max.y / tileSize);

  for (var x = minX; x <= maxX; x++) {
    for (var y = minY; y <= maxY; y++) {
      activeTiles[z+':'+x+':'+y] = true;
    }
  }
};

DynamicLabel.prototype.submitPositionJob = function(job, onmessage) {
  var worker = this.positionWorkerPool.pop();
  if (!worker) {
    console.log('Enqueuing job for position worker...');
    this.positionWorkerQueue.push({job:job, onmessage:onmessage});
  } else {
    worker.onmessage = onmessage;
    worker.postMessage(job);
  }
};

DynamicLabel.prototype.freePositionWorker = function(worker) {
  if (this.positionWorkerQueue.length > 0) {
    var job = this.positionWorkerQueue.shift();
    worker.onmessage = job.onmessage;
    worker.postMessage(job.job);
  } else {
    this.positionWorkerPool.push(worker);
  }
};