How to use the @turf/meta.featureEach function in @turf/meta

To help you get started, we’ve selected a few @turf/meta examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cheeaun / taxirouter-sg / assets / turf.js View on Github external
function nearestPoint(targetPoint, points) {
    // Input validation
    if (!targetPoint) throw new Error('targetPoint is required');
    if (!points) throw new Error('points is required');

    var nearest;
    var minDist = Infinity;
    meta.featureEach(points, function (pt, featureIndex) {
        var distanceToPoint = distance(targetPoint, pt);
        if (distanceToPoint < minDist) {
            nearest = clone(pt);
            nearest.properties.featureIndex = featureIndex;
            nearest.properties.distanceToPoint = distanceToPoint;
            minDist = distanceToPoint;
        }

    });
    return nearest;
}
github Turfjs / turf / packages / turf-line-intersect / index.ts View on Github external
line2.type === "Feature" &&
        line1.geometry !== null &&
        line2.geometry !== null &&
        line1.geometry.type === "LineString" &&
        line2.geometry.type === "LineString" &&
        line1.geometry.coordinates.length === 2 &&
        line2.geometry.coordinates.length === 2) {
        const intersect = intersects(line1, line2);
        if (intersect) { results.push(intersect); }
        return featureCollection(results);
    }

    // Handles complex GeoJSON Geometries
    const tree = rbush();
    tree.load(lineSegment(line2));
    featureEach(lineSegment(line1), (segment) => {
        featureEach(tree.search(segment), (match) => {
            const intersect = intersects(segment, match);
            if (intersect) {
                // prevent duplicate points https://github.com/Turfjs/turf/issues/688
                const key = getCoords(intersect).join(",");
                if (!unique[key]) {
                    unique[key] = true;
                    results.push(intersect);
                }
            }
        });
    });
    return featureCollection(results);
}
github Turfjs / turf / packages / turf-distance-weight / index.ts View on Github external
threshold?: number;
  p?: number;
  binary?: boolean;
  alpha?: number;
  standardization?: boolean;
}): number[][] {

  options = options || {};
  const threshold = options.threshold || 10000;
  const p = options.p || 2;
  const binary = options.binary || false;
  const alpha = options.alpha || -1;
  const rowTransform = options.standardization || false;

  const features: Array> = [];
  featureEach(fc, (feature) => {
    features.push(centroid(feature));
  });

  // computing the distance between the features
  const weights: number[][] = [];
  for (let i = 0; i < features.length; i++) {
    weights[i] = [];
  }

  for (let i = 0; i < features.length; i++) {
    for (let j = i; j < features.length; j++) {
      if (i === j) {
        weights[i][j] = 0;
      }
      const dis = pNormDistance(features[i], features[j], p);
      weights[i][j] = dis;
github Turfjs / turf / packages / turf-interpolate / index.js View on Github external
case 'squares':
        grid = squareGrid(box, cellSize, {units: units});
        break;
    case 'hex':
    case 'hexes':
        grid = hexGrid(box, cellSize, {units: units});
        break;
    case 'triangle':
    case 'triangles':
        grid = triangleGrid(box, cellSize, {units: units});
        break;
    default:
        throw new Error('invalid gridType');
    }
    var results = [];
    featureEach(grid, function (gridFeature) {
        var zw = 0;
        var sw = 0;
        // calculate the distance from each input point to the grid points
        featureEach(points, function (point) {
            var gridPoint = (gridType === 'point') ? gridFeature : centroid(gridFeature);
            var d = distance(gridPoint, point, units);
            var zValue;
            // property has priority for zValue, fallbacks to 3rd coordinate from geometry
            if (property !== undefined) zValue = point.properties[property];
            if (zValue === undefined) zValue = point.geometry.coordinates[2];
            if (zValue === undefined) throw new Error('zValue is missing');
            if (d === 0) zw = zValue;
            var w = 1.0 / Math.pow(d, weight);
            sw += w;
            zw += w * zValue;
        });
github Turfjs / turf / packages / turf-buffer / index.js View on Github external
if (steps <= 0) throw new Error('steps must be greater than 0');

    // default params
    steps = steps || 64;
    units = units || 'kilometers';

    var results = [];
    switch (geojson.type) {
    case 'GeometryCollection':
        geomEach(geojson, function (geometry) {
            var buffered = bufferFeature(geometry, radius, units, steps);
            if (buffered) results.push(buffered);
        });
        return featureCollection(results);
    case 'FeatureCollection':
        featureEach(geojson, function (feature) {
            var multiBuffered = bufferFeature(feature, radius, units, steps);
            if (multiBuffered) {
                featureEach(multiBuffered, function (buffered) {
                    if (buffered) results.push(buffered);
                });
            }
        });
        return featureCollection(results);
    }
    return bufferFeature(geojson, radius, units, steps);
}
github Turfjs / turf / packages / turf-clusters-kmeans / index.ts View on Github external
var data = coordAll(points);

    // create seed to avoid skmeans to drift
    var initialCentroids = data.slice(0, options.numberOfClusters);

    // create skmeans clusters
    var skmeansResult = skmeans(data, options.numberOfClusters, initialCentroids);

    // store centroids {clusterId: [number, number]}
    var centroids = {};
    skmeansResult.centroids.forEach(function (coord, idx) {
        centroids[idx] = coord;
    });

    // add associated cluster number
    featureEach(points, function (point, index) {
        var clusterId = skmeansResult.idxs[index];
        point.properties.cluster = clusterId;
        point.properties.centroid = centroids[clusterId];
    });

    return points;
}
github Turfjs / turf / packages / turf-standard-deviational-ellipse / index.js View on Github external
// Calculate mean center:
    var meanCenter = centerMean(points, {weight: weight});

    // Calculate angle of rotation:
    // [X, Y] = mean center of all [x, y].
    // theta = arctan( (A + B) / C )
    // A = sum((x - X)^2) - sum((y - Y)^2)
    // B = sqrt(A^2 + 4(sum((x - X)(y - Y))^2))
    // C = 2(sum((x - X)(y - Y)))

    var xDeviationSquaredSum = 0;
    var yDeviationSquaredSum = 0;
    var xyDeviationSum = 0;

    featureEach(points, function(point){
      xDeviation = getCoords(point)[0] - getCoords(theMeanCenter)[0];
      yDeviation = getCoords(point)[1] - getCoords(theMeanCenter)[1];
      xDeviationSquaredSum += Math.pow(xDeviation, 2);
      yDeviationSquaredSum += Math.pow(yDeviation, 2);
      xyDeviationSum += xDeviation * yDeviation;
    });

    var bigA = xDeviationSquaredSum - yDeviationSquaredSum;
    var bigB = Math.sqrt(Math.pow(bigA, 2) + 4 * Math.pow(xyDeviationSum, 2));
    var bigC = 2 * xyDeviationSum;
    var theta = Math.atan((bigA + bigB) / bigC);

    // Calculate axes:
    // sigmaX = sqrt((1 / n - 2) * sum((((x - X) * cos(theta)) - ((y - Y) * sin(theta)))^2))
    // sigmaY = sqrt((1 / n - 2) * sum((((x - X) * sin(theta)) - ((y - Y) * cos(theta)))^2))
    var sigmaXsum = 0;
github Turfjs / turf / packages / turf-buffer / index.js View on Github external
featureEach(geojson, function (feature) {
            var multiBuffered = bufferFeature(feature, radius, units, steps);
            if (multiBuffered) {
                featureEach(multiBuffered, function (buffered) {
                    if (buffered) results.push(buffered);
                });
            }
        });
        return featureCollection(results);
github Turfjs / turf / packages / turf-combine / index.ts View on Github external
var multiMapping = Object.keys(groups).reduce(function (memo, item) {
        memo[item.replace('Multi', '')] = item;
        return memo;
    }, {});

    function addToGroup(feature, key, multi) {
        if (!multi) {
            groups[key].coordinates.push(feature.geometry.coordinates);
        } else {
            groups[key].coordinates = groups[key].coordinates.concat(feature.geometry.coordinates);
        }
        groups[key].properties.push(feature.properties);
    }

    featureEach(fc, function (feature) {
        if (!feature.geometry) return;
        if (groups[feature.geometry.type]) {
            addToGroup(feature, feature.geometry.type, true);
        } else if (multiMapping[feature.geometry.type]) {
            addToGroup(feature, multiMapping[feature.geometry.type], false);
        }
    });

    return featureCollection(Object.keys(groups)
        .filter(function (key) {
            return groups[key].coordinates.length;
        })
        .sort()
        .map(function (key) {
            var geometry = { type: key, coordinates: groups[key].coordinates };
            var properties = { collectedProperties: groups[key].properties };
github Turfjs / turf / packages / turf-concave / index.ts View on Github external
function removeDuplicates(points: FeatureCollection): FeatureCollection {
    const cleaned: Array> = [];
    const existing: {[key: string]: boolean} = {};

    featureEach(points, (pt) => {
        if (!pt.geometry) { return; }
        const key = pt.geometry.coordinates.join("-");
        if (!existing.hasOwnProperty(key)) {
            cleaned.push(pt);
            existing[key] = true;
        }
    });
    return featureCollection(cleaned);
}