How to use @turf/meta - 10 common examples

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-mask / index.js View on Github external
function unionPolygons(polygons) {
    if (polygons.features.length <= 1) return polygons;

    var tree = createIndex(polygons);
    var results = [];
    var removed = {};

    flattenEach(polygons, function (currentFeature, currentIndex) {
        // Exclude any removed features
        if (removed[currentIndex]) return true;

        // Don't search for itself
        tree.remove({index: currentIndex}, filterByIndex);
        removed[currentIndex] = true;

        // Keep applying the union operation until no more overlapping features
        while (true) {
            var bbox = turfBBox(currentFeature);
            var search = tree.search({
                minX: bbox[0],
                minY: bbox[1],
                maxX: bbox[2],
                maxY: bbox[3]
            });
github Turfjs / turf / src / concave / lib / turf-polygon-dissolve.ts View on Github external
export default function polygonDissolve(
    geojson: FeatureCollection,
    options: {mutate?: boolean} = {},
): Feature | null {
    // Validation
    if (getType(geojson) !== "FeatureCollection") { throw new Error("geojson must be a FeatureCollection"); }
    if (!geojson.features.length) { throw new Error("geojson is empty"); }

    // Clone geojson to avoid side effects
    // Topojson modifies in place, so we need to deep clone first
    if (options.mutate === false || options.mutate === undefined) { geojson = clone(geojson); }

    const geoms: any[] = [];
    flattenEach(geojson, (feature) => {
        geoms.push(feature.geometry);
    });
    const topo: any = topology({geoms: geometryCollection(geoms).geometry});
    const merged: any = merge(topo, topo.objects.geoms.geometries);
    return merged;
}
github Turfjs / turf / packages / turf-polygonize / lib / Graph.js View on Github external
static fromGeoJson(geoJson) {
        validateGeoJson(geoJson);

        const graph = new Graph();
        flattenEach(geoJson, feature => {
            featureOf(feature, 'LineString', 'Graph::fromGeoJson');
            // When a LineString if formed by many segments, split them
            coordReduce(feature, (prev, cur) => {
                if (prev) {
                    const start = graph.getNode(prev),
                        end = graph.getNode(cur);

                    graph.addEdge(start, end);
                }
                return cur;
            });
        });

        return graph;
    }