How to use @turf/centroid - 10 common examples

To help you get started, we’ve selected a few @turf/centroid 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 Turfjs / turf / packages / turf-idw / index.js View on Github external
var filtered = controlPoints.features.filter(function (feature) {
        return feature.properties &&
            feature.properties.hasOwnProperty(valueField);
    });
    if (filtered.length === 0) throw new Error('Specified Data Field is Missing');

    // create a sample square grid
    // compared to a point grid helps visualizing the output (like a raster..)
    var samplingGrid = squareGrid(bbox(controlPoints), cellWidth, units);
    var N = samplingGrid.features.length;
    for (var i = 0; i < N; i++) {
        var zw = 0;
        var sw = 0;
        // calculate the distance from each control point to cell's centroid
        for (var j = 0; j < controlPoints.features.length; j++) {
            var d = distance(centroid(samplingGrid.features[i]), controlPoints.features[j], units);
            if (d === 0) {
                zw = controlPoints.features[j].properties[valueField];
            }
            var w = 1.0 / Math.pow(d, weight);
            sw += w;
            zw += w * controlPoints.features[j].properties[valueField];
        }
        // write IDW value for each grid cell
        samplingGrid.features[i].properties[valueField] = zw / sw;
    }
    return samplingGrid;
}
github Turfjs / turf / packages / turf-center-of-mass / index.ts View on Github external
function centerOfMass<p>(geojson: any, options: {
    properties?: P,
} = {}): Feature {
    switch (getType(geojson)) {
    case 'Point':
        return point(getCoord(geojson), options.properties);
    case 'Polygon':
        var coords = [];
        coordEach(geojson, function (coord) {
            coords.push(coord);
        });

        // First, we neutralize the feature (set it around coordinates [0,0]) to prevent rounding errors
        // We take any point to translate all the points around 0
        var centre = centroid(geojson, {properties: options.properties});
        var translation = centre.geometry.coordinates;
        var sx = 0;
        var sy = 0;
        var sArea = 0;
        var i, pi, pj, xi, xj, yi, yj, a;

        var neutralizedPoints = coords.map(function (point) {
            return [
                point[0] - translation[0],
                point[1] - translation[1]
            ];
        });

        for (i = 0; i &lt; coords.length - 1; i++) {
            // pi is the current point
            pi = neutralizedPoints[i];</p>
github Turfjs / turf / packages / turf-kernel_density / index.js View on Github external
m = getCoord(centroid),
                // added latitude correction factor to finetune the 'radiansToLength' function
                latCorrection = Math.cos(degreesToRadians(m[1])),
                _sum = featureReduce(output, (prev, current) => {
                    let
                        w = isWeighted ? (current.properties[weight] || 0) : 1,
                        c = getCoord(current).map((a, i) => Math.pow(w * a - m[i], 2));
                    return prev.map((a, i) => a + c[i]);
                }, [0, 0]),
                degDist = Math.sqrt((_sum[0] + _sum[1]) / pointsCount);
            return radiansToLength(degreesToRadians(degDist), 'kilometers') / latCorrection;
        };

    // find collection's centroid
    if (weight === undefined || weight.length === 0) {
        mc = centroid(output, {
            'weight': null
        });
    } else {
        let
            mw = propReduce(output, (prev, current) => prev + current[weight] * 1, 0),
            _weighted = featureReduce(output, (prev, current) => {
                const
                    w = current.properties[weight],
                    c = getCoord(current).map(a => a * w / mw);
                return prev.map((a, i) => a + c[i]);
            }, [0, 0]);
        mc = point(_weighted, {
            'weight': mw
        });
    }
    // calc the median distance from the centroid to each point (km)
github PieceMaker / max-inscribed-circle / test / max-inscribed-circle.spec.js View on Github external
it('should return the centroid when no Voronoi vertices are inside polygon', function()
    {
        expect(maxCircle(this.inputTinyPolygon).geometry).to.eql(centroid(this.inputTinyPolygon).geometry);
    });
});
github mapstertech / mapbox-gl-draw-rotate-mode / index.js View on Github external
onMouseDown: function(state, e) {
      if(e.featureTarget) {
        if(this._ctx.api.get(e.featureTarget.properties.id)) {
          e.target['dragPan'].disable();
          state.selectedFeature = this._ctx.api.get(e.featureTarget.properties.id);
          state.originalCenter = centroid(e.featureTarget);
          state.originalFeature = e.featureTarget;
          emitter.emit('rotatestart');
        }
      }
      return state;
    },
github Turfjs / turf / packages / turf-nearest-neighbor-analysis / index.ts View on Github external
featureEach(dataset, (feature) => {
        features.push(centroid(feature));
    });
    const n = features.length;
github Turfjs / turf / packages / turf-distance-weight / index.ts View on Github external
featureEach(fc, (feature) => {
    features.push(centroid(feature));
  });
github uber / nebula.gl / modules / layers / src / mode-handlers / rotate-handler.js View on Github external
getRotateAction(startDragPoint: Position, currentPoint: Position, editType: string): EditAction {
    const startPosition = startDragPoint;
    const centroid = turfCentroid(this._geometryBeingRotated);
    const angle = getRotationAngle(centroid, startPosition, currentPoint);

    const rotatedFeatures = turfTransformRotate(this._geometryBeingRotated, angle);

    let updatedData = this.getImmutableFeatureCollection();

    const selectedIndexes = this.getSelectedFeatureIndexes();
    for (let i = 0; i &lt; selectedIndexes.length; i++) {
      const selectedIndex = selectedIndexes[i];
      const movedFeature = rotatedFeatures.features[i];
      updatedData = updatedData.replaceGeometry(selectedIndex, movedFeature.geometry);
    }

    return {
      updatedData: updatedData.getObject(),
      editType,
github uber / nebula.gl / modules / layers / src / mode-handlers / scale-handler.js View on Github external
getScaleAction(startDragPoint: Position, currentPoint: Position, editType: string): EditAction {
    const startPosition = startDragPoint;
    const centroid = turfCentroid(this._geometryBeingScaled);
    const factor = getScaleFactor(centroid, startPosition, currentPoint);
    const scaledFeatures = turfTransformScale(this._geometryBeingScaled, factor, {
      origin: centroid
    });

    let updatedData = this.getImmutableFeatureCollection();

    const selectedIndexes = this.getSelectedFeatureIndexes();
    for (let i = 0; i &lt; selectedIndexes.length; i++) {
      const selectedIndex = selectedIndexes[i];
      const movedFeature = scaledFeatures.features[i];
      updatedData = updatedData.replaceGeometry(selectedIndex, movedFeature.geometry);
    }

    return {
      updatedData: updatedData.getObject(),
github Turfjs / turf / packages / turf-directional-mean / index.ts View on Github external
return;
            } else {
                sigmaSin += sin1;
                sigmaCos += cos1;
                countOfLines += 1;
                sumOfLen += lenOfLine;
                centroidList.push(centroid(currentFeature));
            }
        });
    }

    const cartesianAngle: number = getAngleBySinAndCos(sigmaSin, sigmaCos);
    const bearingAngle: number = bearingToCartesian(cartesianAngle);
    const circularVariance = getCircularVariance(sigmaSin, sigmaCos, countOfLines);
    const averageLength = sumOfLen / countOfLines;
    const centroidOfLines = centroid(featureCollection(centroidList));
    const [averageX, averageY]: number[] = getCoord(centroidOfLines);
    let meanLinestring;
    if (isPlanar) {
        meanLinestring = getMeanLineString([averageX, averageY], cartesianAngle, averageLength, isPlanar);
    } else {
        meanLinestring = getMeanLineString([averageX, averageY], bearingAngle, averageLength, isPlanar);
    }

    return lineString(meanLinestring, {
        averageLength,
        averageX,
        averageY,
        bearingAngle,
        cartesianAngle,
        circularVariance,
        countOfLines,

@turf/centroid

turf centroid module

MIT
Latest version published 3 years ago

Package Health Score

89 / 100
Full package analysis

Popular @turf/centroid functions