How to use turf - 10 common examples

To help you get started, we’ve selected a few turf 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 mapbox / tile-reduce / test / disconnect / disconnect.js View on Github external
module.exports = function(tileLayers, tile, done){
  var bbox = tilebelt.tileToBBOX(tile);
  var minDistance = 50/5280; // 50 ft in miles
  var disconnects = turf.featurecollection([]);
  var caps = [];

  // Types we are looking for disconnected ends for
  var preserve_type = { "motorway" : true, "primary" : true, "secondary" : true, "tertiary" : true, "trunk": true, "residential": true };

  // Classes that we don't want to suggest that they should connect to
  var reject_class = { "major_rail" : true, "minor_rail" : true, "aerialway" : true };

  // First pass: finding road ends that don't connect to anything
  for (var layer in tileLayers.streets) {
    var i, j, k, f, g;

    for (var i = 0; i < tileLayers.streets[layer].features.length; i++) {
      var flat = flatten(tileLayers.streets[layer].features[i]);

      for (var f = 0; f < flat.length; f++) {
github mapbox / tile-reduce / test / disconnect / disconnect.js View on Github external
flat.forEach(function(line) {
          // Don't try to match an endpoint to the way that it came from
          if (layer == cap.layer && i == cap.i) {
            return;
          }

          if (!reject_class[line.properties.class] && line.geometry.type === 'LineString') {
            var distance = turf.distance(cap.point, turf.pointOnLine(line, cap.point));

            if (distance < best) {
              var already = false;

              // Don't try to match an endpoint to a way that the
              // way that it comes from already connects to
              cap.line.geometry.coordinates.forEach(function(capp) {
                line.geometry.coordinates.forEach(function(linep) {
                  if (capp[0] == linep[0] && capp[1] == linep[1]) {
                    already = true;
                  }
                });
              });

              if (!already) {
                best = distance;
github mapbox / tile-reduce / test / diff / diff.js View on Github external
var streets = normalize(tileLayers.streets.road);
  streets.features = streets.features.concat(normalize(flatten(tileLayers.streets.bridge)).features);
  streets.features = streets.features.concat(normalize(flatten(tileLayers.streets.tunnel)).features);

  // clip features to tile
  streets = clip(streets, tile);
  tigerRoads = clip(tigerRoads, tile);
  streets = normalize(flatten(streets));
  tigerRoads = normalize(flatten(tigerRoads));

  // buffer streets
  var streetBuffers = turf.featurecollection([]);
  streetBuffers.features = streets.features.map(function(road){
    return turf.buffer(road, 5, 'meters').features[0];
  });
  streetBuffers = normalize(turf.merge(streetBuffers));

  // erase street buffer from tiger lines
  var tigerDeltas = turf.featurecollection([]);
  tigerRoads.features.forEach(function(tigerRoad){
    streetBuffers.features.forEach(function(streetsRoad){
      var roadDiff = turf.erase(tigerRoad, streetsRoad);
      if(roadDiff) tigerDeltas.features.push(roadDiff);
    });
  });
  tigerDeltas = normalize(flatten(tigerDeltas));

  done(null, {
    diff: tigerDeltas,
    tiger: tigerRoads,
    streets: streets
  });
github naturalatlas / tilemantle / bin / tilemantle.js View on Github external
var coords = String(argv.extent).split(',').map(parseFloat);
			var input = turf.featurecollection([
				turf.point([coords[1], coords[0]]),
				turf.point([coords[3], coords[2]])
			]);
			geojson = turf.extent(input);
		} else {
			displayHelp();
			console.error('No geometry provided. Pipe geojson, or use --point or --extent');
			return process.exit(1);
		}

		if (argv.buffer) {
			var radius = parseFloat(argv.buffer);
			var units = /mi$/.test(argv.buffer) ? 'miles' : 'kilometers';
			geojson = turf.buffer(geojson, radius, units);
		}

		// tilecover doesn't like features
		geojson = turf.merge(geojson);
		if (geojson.type === 'Feature') {
			geojson = geojson.geometry;
		}

		callback();
	},
	function performAction(callback) {
github naturalatlas / tilemantle / bin / tilemantle.js View on Github external
]);
			geojson = turf.extent(input);
		} else {
			displayHelp();
			console.error('No geometry provided. Pipe geojson, or use --point or --extent');
			return process.exit(1);
		}

		if (argv.buffer) {
			var radius = parseFloat(argv.buffer);
			var units = /mi$/.test(argv.buffer) ? 'miles' : 'kilometers';
			geojson = turf.buffer(geojson, radius, units);
		}

		// tilecover doesn't like features
		geojson = turf.merge(geojson);
		if (geojson.type === 'Feature') {
			geojson = geojson.geometry;
		}

		callback();
	},
	function performAction(callback) {
github funkeinteraktiv / cogran / lib / methods / binary-dasymetric-weighting.js View on Github external
let isIntersect = Turf.intersect(d, e);
	  
      if(isIntersect) {
		isIntersect = arealizeGeometryCollection(isIntersect);
        isIntersect.properties = d.properties;
        isIntersect.properties.parentArea = Turf.area(d);
        resultFeatures.push(isIntersect);
      }
    });
	// console.log(resultFeatures);
	// console.log(resultFeatures[0].geometry + ', ' + resultFeatures[0].properties);
	// console.log(Turf.point(resultFeatures[0].geometry[1]));
  });

  return Turf.featurecollection(resultFeatures);
}
github hotosm / osm-analytics / app / components / Map / index.js View on Github external
if (isEditable) {
        boundsLayer.enableEdit()
      }

      // set map view to region
      try { // geometry calculcation are a bit hairy for invalid geometries (which may happen during polygon editing)
        let viewPort = bboxPolygon(map.getBounds().toBBoxString().split(',').map(Number))
        let xorAreaViewPort = erase(viewPort, L.polygon(boundsLayer.getLatLngs()[1]).toGeoJSON())
        let fitboundsFunc
        if (moveDirectly) {
          fitboundsFunc = ::map.fitBounds
          moveDirectly = false
        } else if (
          !xorAreaViewPort // new region fully includes viewport
          || area(xorAreaViewPort) > area(viewPort)*(1-0.01) // region is small compared to current viewport (<10% of the area covered) or feature is outside current viewport
        ) {
          fitboundsFunc = ::map.flyToBounds
        } else {
          fitboundsFunc = () => {}
        }
        fitboundsFunc(
          // zoom to inner ring!
          boundsLayer.getLatLngs().slice(1)
            .map(coords => L.polygon(coords).getBounds())
            .reduce((bounds1, bounds2) => bounds1.extend(bounds2)),
        {
          paddingTopLeft: [20, 10+52],
          paddingBottomRight: [20, 10+ ((fitBoundsWithBottomPadding) ? 212 : 52)]
        })
      } catch(e) {}
    });
github funkeinteraktiv / cogran / lib / methods / binary-dasymetric-weighting-relative.js View on Github external
const sourceList = sourceFeatures.filter(f => {
	//console.log("f: " + Turf.area(f));
	  
	// There might be areas too tiny to be useful and they crash Turf.intersect(featureSimpl, f);
	if (Turf.area(f) < 180) {  // TODO: sinnvollen Wert (à la 1cm) für minimale Fläche finden. Mit 0.1e-10 scheint gut für wenige Testdaten Berlin
		console.log("Dropping Feature with tiny area");
		return;
	}
	  
    let intersection = Turf.intersect(featureSimpl, f);  // This crashes if f is really really small or something. 23.1.2017

    if(!isUndefined(intersection)) {
	  intersection = arealizeGeometryCollection(intersection);
      intersection.properties = f.properties;

      if(f.properties.binary !== 0) {
        intersects.push(intersection);
      }
    }

    return !isUndefined(intersection)// && f.properties.binary !== 0;
  });
github aaronpdennis / congress-maps / process.js View on Github external
// collect bounding boxes for the districts
  var bounds = turf.extent(d);
  districtBboxes[state + number] = bounds;

  // and for the states
  if (stateBboxes[state]) {
    stateBboxes[state].features.push(turf.bboxPolygon(bounds));
  } else {
    stateBboxes[state] = { type: 'FeatureCollection', features: [] };
    stateBboxes[state].features.push(turf.bboxPolygon(bounds));
  }
});

// get the bounding boxes of all of the bounding boxes for each state
for (var s in stateBboxes) {
  stateBboxes[s] = turf.extent(stateBboxes[s]);
}

// write out data for the next steps
console.log('writing data...');

fs.writeFileSync('./data/map.geojson', JSON.stringify(mapData));

fs.writeFileSync('./example/states.js', 'var states = ' + JSON.stringify(stateCodes, null, 2));

var bboxes = {};
for (var b in districtBboxes) { bboxes[b] = districtBboxes[b] };
for (var b in stateBboxes) { bboxes[b] = stateBboxes[b] };
fs.writeFileSync('./example/bboxes.js', 'var bboxes = ' + JSON.stringify(bboxes, null, 2));

console.log('finished processing, ready for tiling');
github mapbox / osrm-matching-inspection / src / match_trace.js View on Github external
function filterGeoJSON(geojson) {
  var outputLine = turf.linestring([]),
      outputGeoJSON = turf.featurecollection([]),
      minTimeDiff = 5, // 12 sampels / minute
      minDistance = 20;

  var feature = geojson.features[0],
      coords = feature.geometry.coordinates,
      times = feature.properties && feature.properties.coordTimes || null,
      prevCoord,
      prevTime,
      newCoords,
      newTimes = [];

  // added no times option
  if (times && !times[0].match(/^\d+$/)) {
    // check if for special fucked up date format.
    if (times[0].match(/^\d\d\d\d-\d-\d\d/)) {
      times = times.map(function (t) {