How to use the @turf/distance function in @turf/distance

To help you get started, we’ve selected a few @turf/distance 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-shortest-path / index.js View on Github external
var box = bbox(scale(bboxPolygon(bbox(collection)), 1.15)); // extend 15%
    if (!resolution) {
        var width = distance([box[0], box[1]], [box[2], box[1]], options);
        resolution = width / 100;
    }
    collection.features.pop();
    collection.features.pop();

    var west = box[0];
    var south = box[1];
    var east = box[2];
    var north = box[3];

    var xFraction = resolution / (distance([west, south], [east, south], options));
    var cellWidth = xFraction * (east - west);
    var yFraction = resolution / (distance([west, south], [west, north], options));
    var cellHeight = yFraction * (north - south);

    var bboxHorizontalSide = (east - west);
    var bboxVerticalSide = (north - south);
    var columns = Math.floor(bboxHorizontalSide / cellWidth);
    var rows = Math.floor(bboxVerticalSide / cellHeight);
    // adjust origin of the grid
    var deltaX = (bboxHorizontalSide - columns * cellWidth) / 2;
    var deltaY = (bboxVerticalSide - rows * cellHeight) / 2;

    // loop through points only once to speed up process
    // define matrix grid for A-star algorithm
    var pointMatrix = [];
    var matrix = [];

    var closestToStart = [];
github uber / nebula.gl / modules / core / src / lib / layers / editable-geojson-layer.js View on Github external
}) {
    const isTranslateFeature =
      this.props.mode === 'modify' &&
      this.props.modeConfig &&
      this.props.modeConfig.action === 'transformTranslate';
    let distanceMoved = 0.02;
    const { pointerMovePicks } = this.state;
    if (
      isTranslateFeature &&
      pointerMovePicks &&
      pointerMovePicks.length &&
      picks &&
      picks.length
    ) {
      distanceMoved = Math.max(
        turfDistance(point(pointerMovePicks[0].lngLat), point(picks[0].lngLat)),
        0.02
      );
    }
    this.setState({ pointerMovePicks: picks });

    if (pointerDownPicks && pointerDownPicks.length > 0) {
      if (isTranslateFeature) {
        sourceEvent.stopPropagation();
        this.handleTransformTranslate(screenCoords, groundCoords, pointerDownPicks, distanceMoved);
        return;
      }
      const editHandleInfo = this.getPickedEditHandle(pointerDownPicks);
      if (editHandleInfo) {
        // TODO: find a less hacky way to prevent map panning
        // Stop propagation to prevent map panning while dragging an edit handle
        sourceEvent.stopPropagation();
github conveyal / analysis-ui / lib / components / import-shapefile.js View on Github external
const mods = shapefile.features.map(feat => {
          const segments = []

          // we make each segment in the input geometry a segment in the output.
          // otherwise adding a stop in the middle would replace all of the surrounding geometry.
          let {coordinates, type} = feat.geometry

          if (type === 'MultiLineString') {
            // flatten the coordinates
            const flat = []

            for (let i = 0; i < coordinates.length; i++) {
              if (i > 0) {
                // make sure they line up at the ends
                if (
                  distance(
                    point(coordinates[i - 1].slice(-1)[0]),
                    point(coordinates[i][0]),
                    'kilometers'
                  ) > 0.05
                ) {
                  this.setState({
                    error: message('shapefile.invalidMultiLineString'),
                    uploading: false
                  })
                  throw new Error('Invalid feature')
                }

                coordinates[i].forEach(c => flat.push(c))
              }
            }
github uber / nebula.gl / modules / main / src / lib / deck-renderer / deck-drawer.js View on Github external
const m = this._getMousePosFromEvent(event);
        this.mousePoints = [m, m];
      }
      redraw = true;
    } else if (event.type === 'mousemove' && landPoints.length) {
      // update last point
      landPoints[landPoints.length - 1] = lngLat;
      mousePoints[mousePoints.length - 1] = this._getMousePosFromEvent(event);
      redraw = true;
    } else if (event.type === 'mouseup') {
      if (usePolygon) {
        // check to see if completed
        // TODO: Maybe double-click to finish?
        if (
          landPoints.length > 4 &&
          turfDistance(landPoints[0], landPoints[landPoints.length - 1]) < POLYGON_THRESHOLD &&
          this.validPolygon
        ) {
          this._selectPolygonObjects();
          this.reset();
          redraw = true;
          deactivate = true;
        }
      } else {
        this._selectRectangleObjects();
        this.reset();
        redraw = true;
        deactivate = true;
      }
    }

    return { redraw, deactivate };
github Turfjs / turf / packages / turf-square-grid / index.ts View on Github external
function squareGrid<p>(bbox: BBox, cellSide: number, options: {
    units?: Units,
    properties?: P,
    mask?: Feature</p>
github uber / nebula.gl / modules / core / src / lib / editable-feature-collection.js View on Github external
_handlePointerMoveForDrawCircleByBoundingBox(groundCoords: Position) {
    if (this._clickSequence.length === 0) {
      // nothing to do yet
      return;
    }

    const firstClickedPoint = this._clickSequence[0];
    const centerCoordinates = getIntermediatePosition(firstClickedPoint, groundCoords);
    const radius = Math.max(distance(firstClickedPoint, centerCoordinates), 0.001);
    this._setTentativeFeature(circle(centerCoordinates, radius));
  }
github Turfjs / turf / packages / turf-center-median / index.ts View on Github external
featureEach(centroids, function (theCentroid: any) {
        var weightValue = theCentroid.properties.weight;
        var weight = (weightValue === undefined || weightValue === null) ? 1 : weightValue;
        weight = Number(weight);
        if (!isNumber(weight)) throw new Error('weight value must be a number');
        if (weight &gt; 0) {
            centroidCount += 1;
            var distanceFromCandidate = weight * distance(theCentroid, candidateMedian);
            if (distanceFromCandidate === 0) distanceFromCandidate = 1;
            var k = weight / distanceFromCandidate;
            candidateXsum += theCentroid.geometry.coordinates[0] * k;
            candidateYsum += theCentroid.geometry.coordinates[1] * k;
            kSum += k;
        }
    });
    if (centroidCount &lt; 1) throw new Error('no features to measure');
github bravecow / mapbox-gl-controls / src / ruler / ruler.js View on Github external
return coordinates.map((coordinate, index) => {
      if (index === 0) return 0;
      sum += distance(coordinates[index - 1], coordinates[index], { units });
      return labelFormat(sum);
    });
  }
github uber / nebula.gl / modules / layers / src / mode-handlers / translate-handler.js View on Github external
getTranslateAction(
    startDragPoint: Position,
    currentPoint: Position,
    editType: string
  ): ?EditAction {
    if (!this._geometryBeforeTranslate) {
      return null;
    }
    const p1 = point(startDragPoint);
    const p2 = point(currentPoint);

    const distanceMoved = turfDistance(p1, p2);
    const direction = turfBearing(p1, p2);

    const movedFeatures = turfTransformTranslate(
      this._geometryBeforeTranslate,
      distanceMoved,
      direction
    );

    let updatedData = this.getImmutableFeatureCollection();

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

@turf/distance

turf distance module

MIT
Latest version published 3 months ago

Package Health Score

96 / 100
Full package analysis

Popular @turf/distance functions