How to use @turf/helpers - 10 common examples

To help you get started, we’ve selected a few @turf/helpers 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
function shortestPath(start, end, options) {
    // Optional parameters
    options = options || {};
    if (!isObject(options)) throw new Error('options is invalid');
    var resolution = options.resolution;
    var minDistance = options.minDistance;
    var obstacles = options.obstacles || featureCollection([]);

    // validation
    if (!start) throw new Error('start is required');
    if (!end) throw new Error('end is required');
    if (resolution && !isNumber(resolution) || resolution <= 0) throw new Error('options.resolution must be a number, greater than 0');
    if (minDistance) throw new Error('options.minDistance is not yet implemented');

    // Normalize Inputs
    var startCoord = getCoord(start);
    var endCoord = getCoord(end);
    start = point(startCoord);
    end = point(endCoord);
github sharedstreets / sharedstreets-js / src / geometry.ts View on Github external
break
      default:
        if (data.id) {
          // Save SharedStreets Intersection GeoJSON Point
          const id = data.id
          const coords = latlonsToCoords(data.latlons)
          const properties = {
            id: data.id,
            fromIntersectionId: data.fromIntersectionId,
            toIntersectionId: data.toIntersectionId,
            forwardReferenceId: data.forwardReferenceId,
            backReferenceId: data.backReferenceId,
            roadClass: data.roadClass,
          }
          // console.log(data.latlons)
          results.push(lineString(coords, properties, {id}))
        }
        // Reset Data
        data.id = null
        data.fromIntersectionId = null
        data.toIntersectionId = null
        data.forwardReferenceId = null
        data.backReferenceId = null
        data.roadClass = null
        data.latlons = []
        return data
    }
  }, {
    id: null,
github CityOfPhiladelphia / mapboard / src / controller / data-manager.js View on Github external
}

    const featuresSorted = this.sortDorParcelFeatures(features);
    let feature;

    if (!multipleAllowed) {
      feature = features[0];
    // dor
    } else {
      feature = featuresSorted[0];
    }

    // use turf to get area and perimeter of all parcels returned
    for (let featureSorted of featuresSorted) {
      // const turfPolygon = polygon(featureSorted.geometry.coordinates);
      const turfPolygon = polygon(featureSorted.geometry.coordinates);
      let turfCoordinates = []
      for (let coordinate of featureSorted.geometry.coordinates[0]) {
        // console.log('coordinate:', coordinate);
        turfCoordinates.push(point(coordinate));
      }

      let distances = []
      for (let i=0; i
github Turfjs / turf / packages / turf-along / index.ts View on Github external
export default function along(
    line: Feature | LineString,
    distance: number,
    options: {units?: Units} = {},
): Feature {
    // Get Coords
    const geom = getGeom(line);
    const coords = geom.coordinates;
    let travelled = 0;
    for (let i = 0; i < coords.length; i++) {
        if (distance >= travelled && i === coords.length - 1) { break;
        } else if (travelled >= distance) {
            const overshot = distance - travelled;
            if (!overshot) { return point(coords[i]);
            } else {
                const direction = bearing(coords[i], coords[i - 1]) - 180;
                const interpolated = destination(coords[i], overshot, direction, options);
                return interpolated;
            }
        } else {
            travelled += measureDistance(coords[i], coords[i + 1], options);
        }
    }
    return point(coords[coords.length - 1]);
}
github conveyal / analysis-ui / lib / components / report / reroute.js View on Github external
if (modification.fromStop && modification.toStop) nStopsRemoved-- // -1 because it's an exclusive interval on both sides, don't include from and to stops

  let nStopsAdded = stops.length

  // the endpoints are included, subtract them off where they overlap with existing stops
  if (modification.fromStop) nStopsAdded--
  if (modification.toStop) nStopsAdded--

  // NB using indices here so we get an object even if fromStop or toStop is null
  // stops in pattern are in fact objects but they only have stop ID.
  const fromStop = feed.stopsById[pattern.stops[fromStopIndex].stop_id]
  const toStop = feed.stopsById[pattern.stops[toStopIndex].stop_id]

  const geometry = lineSlice(
    point([fromStop.stop_lon, fromStop.stop_lat]),
    point([toStop.stop_lon, toStop.stop_lat]),
    {
      type: 'Feature',
      geometry: pattern.geometry,
      properties: {}
    }
  )

  const removedLengthThisPattern = turfLength(geometry)

  return (
    <table>
      <tbody>
        <tr></tr></tbody></table>
github conveyal / analysis-ui / lib / utils / get-existing-stops-along-pattern.js View on Github external
stops.forEach(stop =&gt; {
      // Ignore the source segment's start and end stops
      if (stop.stop_id !== segment.fromStopId &amp;&amp; stop.stop_id !== segment.toStopId) {
        const stopPoint = turf.point([stop.stop_lon, stop.stop_lat])
        if (pointToLineDistance(stopPoint, line) &lt;= STOP_SEARCH_BUFFER_KM) {
          const pointOnLine = nearestPointOnLine(line, stopPoint)
          // Ignore points too close to start or end stops
          if ((!segment.stopAtStart ||
            pointOnLine.properties.location &gt; APPROX_MIN_SPACING_KM) &amp;&amp;
            (!segment.stopAtEnd ||
            segmentLengthKm - pointOnLine.properties.location &gt; APPROX_MIN_SPACING_KM)
          ) {
            pointOnLine.properties.stopId = stop.stop_id
            pointOnLine.properties.stopCoords = [stop.stop_lon, stop.stop_lat]
            candidateStops.push(pointOnLine)
          }
        }
      }
    })
    // cluster stops that are close to each other
github terascope / teraslice / packages / xlucene-evaluator / src / parser / functions / geo / helpers.ts View on Github external
return (fieldData: JoinGeoShape) => {
        let polygon: any;
        if (isGeoShapePoint(fieldData)) {
            return equal(searchPoint, tPoint(fieldData.coordinates));
        }

        if (isGeoShapeMultiPolygon(fieldData)) {
            polygon = multiPolygon(fieldData.coordinates);
        }

        if (isGeoShapePolygon(fieldData)) {
            polygon = tPolygon(fieldData.coordinates);
        }
        // Nothing matches so return false
        if (!polygon) return false;
        return pointInPolygon(searchPoint, polygon);
    };
}
github sensebox / openSenseMap-API / packages / api / lib / transformers / idwTransformer.js View on Github external
idwTransformer.prototype.addMeasurementToAverage = function addMeasurementToAverage (measurement, cb) {
  const value = measurement.value;

  // for breaks
  if (value &lt; this._min) {
    this._min = value;
  }

  if (value &gt; this._max) {
    this._max = value;
  }

  if (!Object.keys(this._averages).includes(measurement.sensorId)) {
    this._averages[measurement.sensorId] = {
      count: 0,
      geom: point([measurement.lon, measurement.lat], { average: value })
    };

    return cb();
  }

  const avg = this._averages[measurement.sensorId];

  avg.count = avg.count + 1;
  avg.geom.properties.average = (
    ((avg.geom.properties.average * avg.count) + value) /
    (avg.count + 1)
  );

  cb();
};
github terascope / teraslice / packages / xlucene-evaluator / src / parser / functions / geo / helpers.ts View on Github external
return (fieldData: JoinGeoShape) => {
        let feature: any;
        if (isGeoShapePoint(fieldData)) {
            feature = tPoint(fieldData.coordinates);
        }

        if (isGeoShapeMultiPolygon(fieldData)) {
            feature = multiPolygon(fieldData.coordinates);
        }

        if (isGeoShapePolygon(fieldData)) {
            feature = tPolygon(fieldData.coordinates);
        }
        // Nothing matches so return false
        if (!feature) return false;
        try {
            return match(feature);
        } catch (err) {
            return false;
        }
github Turfjs / turf / packages / turf-meta / types.ts View on Github external
segmentEach,
    lineReduce,
    lineEach
} from './'

// Fixtures
const pt = helpers.point([0, 0])
const line = helpers.lineString([[0, 0], [1, 1]])
const poly = helpers.polygon([[[0, 0], [1, 1], [0, 1], [0, 0]]])
const multiPoly = helpers.multiPolygon([[[[0, 0], [1, 1], [0, 1], [0, 0]]]])
const multiLine = helpers.multiLineString([[[0, 0], [1, 1], [0, 1], [0, 0]], [[2, 2], [3, 3]]])
const geomCollection = helpers.geometryCollection([pt.geometry, line.geometry])
const features = helpers.featureCollection([pt, line])

const customPoint = point([10, 20], {foo: 'abc', bar: 123})
const customPoints = featureCollection([customPoint])
const customLineString = lineString([[0, 0], [10, 20]], {foo: 'abc', bar: 123})
const customLineStrings = featureCollection([customLineString])

/**
 * meta.coordEach
 */
const coordEachValue: void = meta.coordEach(pt, coords =&gt; coords)
coordEach(pt, (coords, index) =&gt; coords)
meta.coordEach(pt, (coords, index) =&gt; coords)
meta.coordEach(pt.geometry, coords =&gt; { const equal: number[] = coords })
meta.coordEach(line, coords =&gt; { const equal: number[] = coords })
meta.coordEach(poly, coords =&gt; { const equal: number[] = coords })
meta.coordEach(multiPoly, coords =&gt; { const equal: number[] = coords })
meta.coordEach(geomCollection, coords =&gt; coords)

/**