Exemplo n.º 1
0
  query_overpass('[out:json];relation('+id+');>;out;', function(error, data){
    if(!error){
      linestringArray = [];
      pointPolygon = [];

      data.features.forEach(function(entry) {
        if(entry.geometry.type == 'LineString'){
          linestringArray.push(entry.geometry.coordinates);
        }
      });

      var n = linestringArray.length;
      var igeo = 0;

      for (var i = 0; i < n; i++) {
        if(!pointPolygon[igeo]){
          pointPolygon[igeo] = linestringArray[igeo];
          linestringArray.splice(0,1);
        }
        var pointtofind = pointPolygon[igeo][pointPolygon[igeo].length-1];
        linestringArray.forEach(function(entry,index) {
          if(entry[0][0] == pointtofind[0] && entry[0][1] == pointtofind[1]){
            var arraytoadd = entry;
            arraytoadd.splice(0,1);
            pointPolygon[igeo] = pointPolygon[igeo].concat(arraytoadd);
            linestringArray.splice(index,1);
          }
          if(entry[entry.length-1][0] == pointtofind[0] && entry[entry.length-1][1] == pointtofind[1]){
            var arraytoadd = entry.reverse();
            arraytoadd.splice(0,1);
            pointPolygon[igeo] = pointPolygon[igeo].concat(arraytoadd);
            linestringArray.splice(index,1);
          }
        });
        if(
          pointPolygon[igeo][0][0] == pointPolygon[igeo][pointPolygon[igeo].length-1][0]
          && pointPolygon[igeo][0][1] == pointPolygon[igeo][pointPolygon[igeo].length-1][1]
          && linestringArray.length != 0
        ){
          igeo++;
        }
      }

      if(linestringArray.length == 0){
        try {
          var poly1 = turf.polygon(pointPolygon);
          var poly2 = turf.polygon(pointPolygon, {bbox:turf.bbox(poly1)});
          callback(fc([poly2]));
        }
        catch (e) {
           callback(false);
        }
      }else{
        callback(false);
      }
    }else{
      callback(false);
    }

  }, {flatProperties:true});
Exemplo n.º 2
0
var getFootprint = function(xmlDOM, origin, properties) {
  properties = properties || {};

  // Find ground surfaces
  var groundSurfaces = xmldom2xml(xmlDOM.getElementsByTagName('bldg:GroundSurface'));

  // Add origin to properties
  properties.origin = origin;

  var point = turf.point(origin, properties);

  if (!groundSurfaces || groundSurfaces.length === 0) {
    return point;
  }

  try {
    var points;
    var polygons = [];
    for (var i = 0; i < groundSurfaces.length; i++) {
      points = citygmlPoints(groundSurfaces[i]).map((point) => {
        return proj4('EPSG:ORIGIN').inverse([point[0], point[1]]);
      });

      polygons.push(turf.polygon([points], properties));
    }

    var featureCollection = turf.featurecollection(polygons);
    var polygon = turf.merge(featureCollection);

    return polygon;
  } catch(err) {
    console.error(chalk.red(err));
    return point;
  }
};
Exemplo n.º 3
0
 it ('should fail to pull a tile because the cache had an error', function(done) {
   var c = new Cache({
     outputDirectory: cacheDir,
     id: 'cache-test',
     name: 'cache-test',
     minZoom: 0,
     maxZoom: 1,
     geometry: turf.polygon([[
       [-180, -85],
       [-180, 85],
       [180, 85],
       [180, -85],
       [-180, -85]
     ]]),
     cacheCreationParams: {
       noGeoPackageIndex: true
     }
   });
   c.callbackWhenInitialized(function() {
     should.exist(c.error);
     c.getTile('png', 0, 0, 0, function(err, tileStream) {
       should.exist(err);
       should.not.exist(tileStream);
       done();
     });
   });
 });
Exemplo n.º 4
0
	points.forEach(function(point, key){

		var closest = undefined;
		var _closest = undefined;
		var _inside = false;

		point.travelTime = point.travelTime || {};

		//get center point
		var face = turf.polygon([[
			[point.a.lon, point.a.lat],
			[point.b.lon, point.b.lat],
			[point.c.lon, point.c.lat],
			[point.a.lon, point.a.lat]
		]]);

		var center = turf.centroid(face);
		point._center = center;

		map.features.forEach(function(feature){

			var inside = turf.inside(center, feature);

			//inside
			if(inside && (!point.travelTime[year] || point.travelTime[year] > feature.properties.travelTime)){
				_inside = true;
				point.travelTime[year] = feature.properties.travelTime;
			}

			if(!feature.properties.travelTime){
				console.log(feature.properties)
				process.exit();
			}

			//see if this point is closer
			feature.geometry.coordinates[0].forEach(function(coord){

				var distance = turf.distance(center, turf.point(coord));

				if(!closest || distance < closest){
					closest = distance;
					_closest = feature;
				}

			});

		});

		if(!_inside){
			point.travelTime[year] = _closest.properties.travelTime;
		}

		point.center = center.geometry.coordinates;
		console.log('done for gridpoint ' + key + ' of ' + points.length + ' for year ' + year);

	});
Exemplo n.º 5
0
module.exports.area = function(layout) {
  var arc = module.exports.frontArc(layout);
  var properties = arc.properties;
  arc = arc.geometry.coordinates;
  var backArcDistance = utils.feetToMiles(layout.dmz.distance+layout.dmz.depth);
  var backArc = streets.circleStreet(layout.center,layout.bearing,backArcDistance,'miles',layout.dmz.segments,"dmz","DMZ").geometry.coordinates[0];
  var coordinates = arc.concat(backArc.reverse());
  coordinates.push(coordinates[0]);
  return turf.polygon([coordinates],properties);
}
Exemplo n.º 6
0
test('area', function (t) {
    for (var i = 0; i < lines.length; i++) {
        if (lines[i].length < 3) continue;
        var poly = turf.polygon([lines[i].concat([lines[i][0]])]);
        var expected = turf.area(poly) / 1e6;
        var actual = ruler.area([lines[i]]);
        assertErr(t, expected, actual, 0.003, 'area');
    }
    t.pass('area within 0.3%');
    t.end();
});
var boxGeoJSON  = function(width,height,center,bearing,units) {
    var halfSidePont = turf.destination(center,width/2.0,bearing-90,units);
    var firstCorner = turf.destination(halfSidePont,height/2.0,bearing,units);
    var secondCorner = turf.destination(firstCorner,width,bearing+90,units);
    var thirdCorner = turf.destination(secondCorner,height,bearing+180,units);
    var finalCorner = turf.destination(thirdCorner,width,bearing-90,units);
    var points = [firstCorner,secondCorner,thirdCorner,finalCorner,firstCorner];
    points = points.map(function(item){
        return item.geometry.coordinates;
    })
    return turf.polygon([points]);
}
    it('should get create an xyz cache', function(done) {
      this.timeout(0);
      var osmDataSource = {
        name: 'osm',
        url: 'http://osm.geointapps.org/osm',
        format: 'xyz',
        zOrder: 0
      };

      var map = {
        name: 'Cache Route Test',
        dataSources: [osmDataSource]
      };

      var cache = {
        name: 'XYZ',
        minZoom: 0,
        maxZoom: 3,
        geometry: turf.polygon([[
          [-250, -85],
          [-250, 85],
          [-181, 85],
          [-181, -85],
          [-250, -85]
        ]]).geometry
      };

      Map.create(map, function(err, map) {
        createdMap = map;
        log.info('Created a map %s with id %s', map.name, map.id);
        cache.source = map;
        cache.create = ['xyz'];

        Cache.create(cache, function(err, cache) {
          if (err) console.log('err creating cache', err);
          console.log('Created Cache', cache);
          createdCache = cache;
          expect(cache.formats.xyz).to.have.property('complete', true);
          expect(cache.formats.xyz).to.have.property('generatedTiles', 85);
          expect(cache.formats.xyz).to.have.property('totalTiles', 85);
          CacheModel.getCacheById(cache.id, function(err, cache) {
            log.info('cache was created', JSON.stringify(cache, null, 2));
            done();
          });
        }, function(err, cache) {
          console.log('Cache progress', cache);
        });
      });
    });
Exemplo n.º 9
0
 findPointInRegion: function(point, layer) {
   var name = ''
   var x = +point[1]
     , y = +point[0]
   var pt = turf.point(x, y)
   for (var x in layer.features) {
     var feature = layer.features[x]
     var poly = turf.polygon(feature.geometry.coordinates)
     var isInside = turf.inside(pt, poly)
     if (isInside) {
       name = feature.properties.name
       return name
     }
   }
   return name
 },
Exemplo n.º 10
0
    it('should get create a GeoPackage cache', function(done) {
      this.timeout(0);
      var osmDataSource = {
        name: 'osm',
        url: 'http://osm.geointapps.org/osm',
        format: 'xyz',
        zOrder: 0
      };

      var map = {
        name: 'Cache Route Test',
        dataSources: [osmDataSource]
      };

      var cache = {
        name: 'XYZ',
        minZoom: 0,
        maxZoom: 3,
        geometry: turf.polygon([[
          [-180, -85],
          [-180, 85],
          [180, 85],
          [180, -85],
          [-180, -85]
        ]]).geometry
      };

      Map.create(map, function(err, map) {
        createdMap = map;
        var doneCalled = false;
        log.info('Created a map %s with id %s', map.name, map.id);
        cache.source = map;
        cache.create = ['geopackage'];

        Cache.create(cache, function(err, cache) {
          if (err) console.log('err creating cache', err);
          createdCache = cache;
          if (!doneCalled) {
            doneCalled = true;
            done();
          }
        }, function(err, cache) {
          console.log('Cache progress', cache);
        });
      });
    });
Exemplo n.º 11
0
 multi2simple = function(e){
     var e2 = (e.features !== void 0)? e.features[0]: e,
             a=0, j=-1, p, count;
     if (e2.geometry.type=='MultiPolygon'){
         for (i=0;i<e2.geometry.coordinates.length;i++){
             p = pol(e2.geometry.coordinates[i]);
             if (turfarea(p)>a){
                 a = turfarea(p);
                 j=i;
             }
         }
         e2.geometry.coordinates = [e2.geometry.coordinates[j][0]];
         e2.geometry.type='Polygon';
     }
     count = e2.geometry.coordinates.reduce(function(a, b){ return a + b.length; }, 0);  
     return (count > maxcount) ? simplify(e2) : e2;
 };
Exemplo n.º 12
0
const drawCreated = (e) => {

	let type = e.layerType;
	let layer = e.layer;
	//console.log(layer);
	var latlngs = [],
		coords = null,
		featureDrawn = null,
		featureArea = null;
	if (type == 'polyline') {
		console.log("您已画了线");
		layer._latlngs.map((item) => {
			coords = [item.lng, item.lat];
			latlngs.push(coords);
		});
		featureDrawn = turf.lineString(latlngs);
	} else if (type == 'polygon') {
		console.log("您已画了面");
		layer._latlngs[0].map((item) => {
			coords = [item.lng, item.lat];
			latlngs.push(coords);
		});
		//第一个点和最后一个点要保持一致,要不turf解析不了。
		latlngs.push(latlngs[0])
			//console.log('latlng:', latlngs)
		featureDrawn = turf.polygon([latlngs]);
		featureArea = turf.area(featureDrawn);

	} else if (type == "marker") {
		latlngs = [layer._latlng.lng, layer._latlng.lat];
		featureDrawn = turf.point(latlngs);
	} else {
		alert("创建图形失败");
		return;
	}

	console.log(featureArea);


	drawnItemsLayer.addLayer(layer);
}
Exemplo n.º 13
0
 it ('should construct a cache with an error because there is no map', function(done) {
   var c = new Cache({
     outputDirectory: cacheDir,
     id: 'cache-test',
     name: 'cache-test',
     minZoom: 0,
     maxZoom: 1,
     geometry: turf.polygon([[
       [-180, -85],
       [-180, 85],
       [180, 85],
       [180, -85],
       [-180, -85]
     ]]),
     cacheCreationParams: {
       noGeoPackageIndex: true
     }
   });
   c.callbackWhenInitialized(function() {
     should.exist(c.error);
     done();
   });
 });
var extractPentagon = function(parsedData) {

  const NUM_POINTS = 5;

  // Extract '2' from 'P2_LAT' or 'P2_LON'
  var rxPointNumber = /P(.)_L/;
  // Extract 'LAT' from 'P2_LAT'
  var rxPointType = /P._(...)/;

  // Point# -> [Lat, Lon]
  var pointArray = [];

  for (var row = 0; row < parsedData.length ; row++) {
    var rxPointNumberResult = rxPointNumber.exec(parsedData[row][0]);
    if (rxPointNumberResult) {
      var pointNum = rxPointNumberResult[1];
      var rxPointTypeResult = rxPointType.exec(parsedData[row][0]);
      var isLat = rxPointTypeResult[1] == 'LAT';

      var pointIndex = pointNum - 1;
      if (pointArray[pointIndex] === undefined) pointArray[pointIndex] = [];
      pointArray[pointIndex][isLat ? 0 : 1] = parsedData[row][1];
    }
  }
  if (!pointArray.length == NUM_POINTS) {
    console.log('Did not find expected number of points!');
    return undefined;
  }

  console.log(pointArray);
  // turf.polygon requires the polygon ring to be closed. e.g: First and last points must be equal
  pointArray[5] = pointArray[0];
  var pentagon = turf.polygon([pointArray]);
  console.log(pentagon);
  return pentagon;
};
Exemplo n.º 15
0
 mapObj.callbackWhenInitialized(function() {
   cache = new Cache({
     source: mapObj,
     outputDirectory: cacheDir,
     id: 'cache-test',
     name: 'cache-test',
     minZoom: 0,
     maxZoom: 1,
     geometry: turf.polygon([[
       [-180, -85],
       [-180, 85],
       [180, 85],
       [180, -85],
       [-180, -85]
     ]]),
     cacheCreationParams: {
       noGeoPackageIndex: true
     }
   });
   cache.callbackWhenInitialized(function() {
     should.not.exist(cache.error);
     done();
   });
 });
Exemplo n.º 16
0
Upper Left  (  512651.296, 4391240.166) (104d51' 8.98"W, 39d40'15.19"N) (-104.852494, 39.670886)
Lower Left  (  512651.296, 4388316.166) (104d51' 9.18"W, 39d38'40.34"N) (-104.85255, 39.644539)
Upper Right (  515154.296, 4391240.166) (104d49'23.92"W, 39d40'15.04"N) (-104.823311, 39.670844)
Lower Right (  515154.296, 4388316.166) (104d49'24.16"W, 39d38'40.20"N) (-104.823378, 39.6445)
Center      (  513902.796, 4389778.166) (104d50'16.56"W, 39d39'27.69"N)
*/

var cacheModel = {
  id: 'test-cache',
  name: 'generic test cache',
  minZoom: 0,
  maxZoom: 3,
  geometry: turf.polygon([[
    [-179, -85],
    [-179, 85],
    [179, 85],
    [179, -85],
    [-179, -85]
  ]]),
  source: mapModel,
  outputDirectory: '/tmp/mapcache-test'
};

var tmpImage = '/tmp/geotiff_test.png';

describe('tms cache creation tests', function() {
  var map;
  var cache;
  before(function(done) {
    this.timeout(10000);
    fs.mkdirsSync(cacheModel.outputDirectory);
Exemplo n.º 17
0
 'turf.area': function () {
     for (var i = 0; i < polygons.length; i++) {
         turf.area(turf.polygon(polygons[i]));
     }
 },
Exemplo n.º 18
0
function inquireGeometry(query, obj) {

	// Match balanced parentheses. It's a bit messy.
	while (query.match(/\(/)) {
		innerQuery = ""
		paraCount = 0

		var paraLeft = query.search(/\(/)
		var paraRight = 0

		for (var i = paraLeft + 1; i < query.length; i++) {

			if (query[i] == ")" && !paraCount) {
				paraRight = i + 1
				break
			}

			innerQuery += query[i]

			if (query[i] == "(") {
				paraCount++
			} else if (query[i] == ")") {
				paraCount--
			}
		}

		var q0 = query.substring(0, paraLeft)
		var q1 = inquireGeometry(innerQuery, obj)
		var q2 = query.substring(paraRight)

		return inquireGeometry(q0 + q1 + q2, obj)
	}

	if (query.split(/&(.+)?/)[1]) {
		return inquireGeometry(query.split(/&(.+)?/)[0], obj) && inquireGeometry(query.split(/&(.+)?/)[1], obj)
	}
	if (query.split(/\|(.+)?/)[1]) {
		return inquireGeometry(query.split(/\|(.+)?/)[0], obj) || inquireGeometry(query.split(/\|(.+)?/)[1], obj)
	}
	if (query == "true") {
		return true
	}
	if (query == "false") {
		return false
	}

	var expect = true
	if (!query.indexOf("!")) {
		expect = false
		query = query.substring(1)
	}

	var arr = query.split(";")
	var arr2 = []
	arr.forEach(function(item) {
		arr2.push([parseFloat(item.split(",")[0]), parseFloat(item.split(",")[1])])
	})
	var type = "Point"
	var feature
	if (arr2.length == 1) {
		feature = turf.point(arr2[0])
	} else if(arr2.length == 2) {
		type = "LineString"
		feature = turf.linestring(arr2)
	} else {
		type = "Polygon"
		arr2.push(arr2[0])
		feature = turf.polygon([arr2])
	}

	var result = !expect

	if (obj.geometry.type == "Point" && type == "Point") {
		result = (obj.geometry.coordinates[0] == feature.geometry.coordinates[0] && obj.geometry.coordinates[1] == feature.geometry.coordinates[1])
	}
	if (obj.geometry.type == "Polygon" && type == "Polygon") {
		result = (turf.intersect(obj, feature) != undefined)
	}
	if (obj.geometry.type == "Point" && type == "Polygon") {
		result = (turf.inside(obj, feature))
	}
	if (obj.geometry.type == "Polygon" && type == "Point") {
		result = (turf.inside(feature, obj))
	}

	if (obj.geometry.type == "LineString" && type == "Polygon"){
		result = false
		var linestring = turf.linestring(feature.geometry.coordinates[0])
		if(lineIntersect(linestring.geometry, obj.geometry)){
			result = true
		} else {
			for (var i = 0; i < obj.geometry.coordinates.length; i++) {
				point = turf.point(obj.geometry.coordinates[i])
				if(turf.inside(point, feature)){
					result = true
					break
				}
			}
		}
	}

	if (obj.geometry.type == "Polygon" && type == "LineString"){
		result = false
		var linestring = turf.linestring(obj.geometry.coordinates[0])
		if(lineIntersect(linestring.geometry, feature.geometry)){
			result = true
		} else {
			for (var i = 0; i < feature.geometry.coordinates.length; i++) {
				point = turf.point(feature.geometry.coordinates[i])
				if(turf.inside(point, obj)){
					result = true
					break
				}
			}
		}
	}

	if (obj.geometry.type == "LineString" && type == "LineString"){
		if(lineIntersect(obj.geometry, feature.geometry)){
			result = true
		}
	}
	return (expect == result)

}
Exemplo n.º 19
0
  	findViewableBuildings: function(polygon, body, latlon) {
    	var result = JSON.parse(body).elements 	
	    var buildings = []
	    var bodyString = body
	    var coords = []
	    var splitPolygon = polygon.split(" ")
	    var viewArea = turf.polygon([[
	      [Number(splitPolygon[1]), Number(splitPolygon[0])], 
	      [Number(splitPolygon[3]), Number(splitPolygon[2])], 
	      [Number(splitPolygon[5]), Number(splitPolygon[4])],
	      [Number(splitPolygon[1]), Number(splitPolygon[0])]
	    ]]) 
	    //check if element (building) is visible or not
	    for (element in result) {
	      	if (latlon!="") {
	        	var split = latlon.split(",")
	        	var lat = Number(split[0])
	        	var lon = Number(split[1])
	      	} else {
	        	var split = polygon.split(" ")
	        	var lat = Number(split[0])
	        	var lon = Number(split[1])
	      	}
      	var point = turf.point([lon, lat]); //origin
      	var poly1status = true
      	var poly2status = true
      	var poly3status = true
      	var poly4status = true
      	var poly5status = true
      	var add = true
      	var nodes = result[element].geometry //get all nodes of the building
      	var building = ""
      	var bounds = this.boundingBoxAroundPolyCoords(nodes)
      	var poly1 = turf.linestring([[lon, lat], [bounds[0][1], bounds[0][0]]])
      	var poly2 = turf.linestring([[lon, lat],[bounds[1][1], bounds[1][0]]])
        var poly3 = turf.linestring([[lon, lat],[bounds[2][1], bounds[2][0]]])
        var poly4= turf.linestring([[lon, lat],[bounds[3][1], bounds[3][0]]])
        var poly5 = turf.linestring([[lon, lat],[(bounds[0][1]+bounds[2][1])/2, (bounds[1][0]+bounds[3][0])/2]])
        var t1 = [(bounds[0][1]+bounds[2][1])/2, (bounds[1][0]+bounds[3][1])/2]
        var bbPoint1 = turf.point([bounds[0][1], bounds[0][0]])
        var bbPoint2 = turf.point([bounds[1][1], bounds[1][0]])
        var bbPoint3 = turf.point([bounds[2][1], bounds[2][0]])
        var bbPoint4 = turf.point([bounds[3][1], bounds[3][0]] )
        var boundsEl = result[element].bounds
        var array5 = [(Number(boundsEl.minlon)+Number(boundsEl.maxlon))/2, (Number(boundsEl.minlat)+Number(boundsEl.maxlat))/2]
        var bbPoint5 = turf.point(array5)
        var typeEl = result[element].tags.building
        var distanceEl = Math.sqrt(Math.pow(lon-array5[0],2)+Math.pow(lat-array5[1],2))
        var levelsEl = 0
        var heightEl = 0
        
        if (result[element].tags['building:levels']!=undefined) {
        	levelsEl = Number(result[element].tags['building:levels']) 
        }
        if (result[element].tags.height!=undefined) {
        	heightEl = Number(result[element].tags.height)
        }
        
        //check if lines intersect one of the found buildings
            for (x in result) {
              	if (result[x].id != result[element].id) {
                	var boundsX = this.boundingBoxAroundPolyCoords(result[x].geometry)
                	var levelsB = 0
                	var heightB = 0
                	var typeB = result[x].tags.building
                	if (result[x].tags['building:levels']!=undefined) {
			        	levelsB = Number(result[x].tags['building:levels']) 
			        }
			        if (result[x].tags.height!=undefined) {
			        	heightB = Number(result[x].tags.height)
			        }
                	var bbox = [
                  		Number(result[x].bounds.minlon), 
                  		Number(result[x].bounds.minlat), 
                  		Number(result[x].bounds.maxlon), 
                  		Number(result[x].bounds.maxlat)
                	]
                	var distanceB = Math.sqrt(Math.pow(lon-((bbox[0]+bbox[2])/2),2)+Math.pow(lat-((bbox[1]+bbox[3])/2),2))
                	var nodesX = result[x].geometry
                    var coordsX = []
                    for (node in nodesX) {
                      var lat = Number(nodesX[node].lat)
                      var lon = Number(nodesX[node].lon)
                      coordsX.push([lon,lat])               
                    }
                    coordsX.push(coordsX[0])
	                try { 
	                  var poly = turf.polygon([coordsX])
	                } catch(err) {
	                  console.log("TURF ERROR: " + err)
	                  break
	                }
	                var heightRatio = 0
	                if (heightEl>heightB && heightB!=0) {            	
	                	heightRatio = (heightEl*distanceB)/(heightB*distanceEl)
	                } else if (levelsEl>levelsB && levelsB!=0) {   
	                	heightRatio = (levelsEl*distanceB)/(levelsB*distanceEl)
	                } 
	                if (heightRatio>1) {
			        } else {
		                if (poly1status) {	                    
		                    if (!(turf.inside(bbPoint1,viewArea))) {
		                    	poly1status = false
		                  	} else {
		                  		var intersection1 = turf.intersect(poly1, poly)	 
		                  		if ((intersection1!=undefined) && (intersection1.geometry.type!="Point")) {
									poly1status = false								
		                  		}
		                  	} 
		                }
		                if (poly2status) {
		                   	if (!(turf.inside(bbPoint2,viewArea))) {
		                    	poly2status = false
		                  	} else {
		                  		var intersection2 = turf.intersect(poly2, poly)	 
		                  		if ((intersection2!=undefined) && (intersection2.geometry.type!="Point")) {
									poly2status = false
		                  		}
		                  	}
		                }
		                if (poly3status) {
		                  	if (!(turf.inside(bbPoint3,viewArea))) {
		                    	poly3status = false
		                  	} else {
		                  		var intersection3 = turf.intersect(poly3, poly)	 
		                  		if ((intersection3!=undefined) && (intersection3.geometry.type!="Point")) {
									poly3status = false
		                  		}
		                  	}
		                }
		                if (poly4status) {
		                   	if (!(turf.inside(bbPoint4,viewArea))) {
		                    	poly4status = false
		                  	} else {
		                  		var intersection4 = turf.intersect(poly4, poly)	 
		                  		if ((intersection4!=undefined) && (intersection4.geometry.type!="Point")) {
									poly4status = false
		                  		}
		                  	}
		                }
		                if (poly5status) {
		                  	if (!(turf.inside(bbPoint5,viewArea))) {
		                    	poly5status = false
		                  	} else {
		                  		var intersection5 = turf.intersect(poly5, poly)	 
		                  		if ((intersection5!=undefined) && (intersection5.geometry.type!="Point")) {
									poly5status = false
		                  		}
		                  	}
		                }
	            	}
	                if ((poly1status==false) && (poly2status==false) && (poly3status==false) && (poly4status==false) && (poly5status==false)) {
	                  	add = false
	                  	break
	                }                
              	}
            }
            //if element(building) is not hidden behind any other building --> save it
            if (add) {
              	var geometry = []
              	for (node in nodes) {
                    var lat = Number(nodes[node].lat)
                    var lon = Number(nodes[node].lon)
                    var oneNode = proj4(proj4('EPSG:4326'), proj4('EPSG:3857'), [ lon, lat ])
                    geometry.push(oneNode)
              	}
                buildings.push({ id: result[element].id, geometry: [geometry] }) 
            }  
        }
        return buildings
  	}
Exemplo n.º 20
0
Object.keys(tiles).forEach(function(tile){
  var poly = turf.polygon(tilebelt.tileToGeoJSON(tile.split('/').map(parseFloat)).coordinates);
  poly.properties = tiles[tile];
  fc.features.push(poly);
});
Exemplo n.º 21
0
        jsonfile.readFile(landmarks_file, function(landmarks_err, landmarks_data) {
            console.log('Loaded landmarks');
            var q;
            for (q = 0; q < population_data.data.length; q++) {
                populations[population_data.data[q][12]] = population_data.data[q][13];
            }
            
            for (tract_index in data.features) {
                var coords = data.features[tract_index].geometry.coordinates;
                var turf_polygon = {
                    "type": "Feature",
                    "properties": {},
                    "geometry": {
                        "type": "Polygon",
                        "coordinates": coords
                    }
                };
                turf_polygons[tract_index] = turf_polygon;
            }
            
            var i;
            var j;
            var demand = [];
            for (var a = 0; a < voxels_dim; a++) {
                var dim = [];
                for (var b = 0; b < voxels_dim; b++) {
                    dim.push(0.0);
                }
                demand.push(dim);
            }
            
            var landmark_polygons_of_interest = {"JFK Airport": 0, "LaGuardia Airport": 0, "Grand Central": 0, "Port Authority Bus Terminal": 0, "Penn Station": 0};
            var landmark_scalers = {"JFK Airport": 11000.0, "LaGuardia Airport": 9000.0, "Grand Central": 2000.0, "Port Authority Bus Terminal": 1000.0, "Penn Station": 2000.0};
            
            for (landmark_index = 0; landmark_index < landmarks_data["features"].length; landmark_index++) {
                var landmark = landmarks_data["features"][landmark_index];
                var landmark_name = landmark["properties"]["name"];
                if (landmark_name in landmark_polygons_of_interest) {
                    //console.log(landmark["geometry"]["coordinates"]);
                    var landmark_polygon = turf.polygon(landmark["geometry"]["coordinates"]);
                    landmark_polygons_of_interest[landmark_name] = landmark_polygon;
                    var landmark_centroid = turf.centroid(landmark_polygon);
                    console.log("Landmark "+landmark_name+" centroid in polygon: "+turf.inside(landmark_centroid, landmark_polygon));
                }
            }
            
            
            console.log("Calculating centroids");
            var centroids = [];
            for (tract_index = 0; tract_index < data.features.length; tract_index++) {
                var turf_centroid = turf.centroid(data.features[tract_index]);
                //var tract_area = turf.area(turf_polygons[tract_index]);
                centroids[tract_index] = turf_centroid;
            }
            
            console.log("Calculating voxels");
            for (i = 0; i < voxels_dim; i++) {
                var lat = lat_min + voxels_res_lat*i;
                for (j = 0; j < voxels_dim; j++) {
                    var lon = lon_min + voxels_res_lon*j;
                    var square = turf.bboxPolygon([lon, lat, lon+voxels_res_lon, lat+voxels_res_lat]);
                    var d = 0.0;
                    
                    for (tract_index = 0; tract_index < data.features.length; tract_index++) {
                        var tract = data.features[tract_index];
                        var ct2010 = tract.properties.TRACTCE10;
                        var centroid = centroids[tract_index];
                        var square_centroid = turf.center({"type": "FeatureCollection", "features": [square]});
                        
                        var distance = turf.distance(centroid, square_centroid, 'miles');
                        
                        if (distance <= 1.0) {
                        
                            var overlap_polygon = turf.intersect(tract, square);
                            if (overlap_polygon != undefined) {
                                
                                var overlap_area = turf.area(overlap_polygon);
                                var tract_area = turf.area(tract);
                                if (ct2010 in populations) {
                                    d += populations[ct2010] * overlap_area/tract_area;
                                } else {
                                    d += 1000.0 * overlap_area/tract_area;
                                }
                            }
                            
                        }
                    }
                    
                    var voxel_center = turf.point([lon + voxels_res_lon/2.0, lat + voxels_res_lat/2.0]);
                    for (lpoi in landmark_polygons_of_interest) {
                        if (turf.inside(voxel_center, landmark_polygons_of_interest[lpoi])) {
                            console.log("Inside "+lpoi);
                            d += 500.0;
                        }
                    }
                    
                    
                    //console.log(d);
                    demand[i][j] = d;
                    //console.log("Finished voxel "+(j+(i*voxels_dim))+" of "+voxels_total);
                    bar.tick();
                    if (bar.complete) {
                        console.log('complete!');
                    }
                }
            }
            
            

            jsonfile.writeFile('demand.json', demand, {spaces: 2}, function(err) {
                console.error(err);
            });
            
        });
Exemplo n.º 22
0
describe('Cache Tests', function() {

  var cacheDir = '/tmp/cache_test';
  var cache;

  var osm = {
    id: 'osm-ds',
    name: 'osm',
    url: 'http://osm.geointapps.org/osm',
    format: 'xyz',
    zOrder: 0
  };

  var rivers = {
    id: 'rivers-ds',
    name: 'rivers',
    file: {
      path: path.join(__dirname, 'format','Rivers.geojson'),
      name: 'Rivers.geojson'
    },
    format: 'geojson',
    zOrder: 2,
    style: {
      defaultStyle: {
        style: getRandomStyle()
      }
    }
  };

  var landHexes = {
    id: 'landhexes-ds',
    name: 'landhexes',
    file: {
      path: '/data/maps/landhexes.json',
      name: 'landhexes'
    },
    format: 'geojson',
    zOrder: 1,
    style: {
      defaultStyle: {
        style: getRandomStyle()
      }
    }
  };

  var map = {
    outputDirectory: cacheDir,
    id: 'test-map',
    name: 'test-map',
    dataSources: [osm, rivers]
  };

  var cacheModel = {
    source: map,
    outputDirectory: cacheDir,
    id: 'cache-test',
    name: 'cache-test',
    minZoom: 0,
    maxZoom: 1,
    geometry: turf.polygon([[
      [-180, -85],
      [-180, 85],
      [180, 85],
      [180, -85],
      [-180, -85]
    ]]),
    cacheCreationParams: {
      noGeoPackageIndex: true
    }
  };

  before(function(done) {
    async.eachSeries([rivers], function(source, callback) {
      FeatureModel.deleteFeaturesBySourceId(source.id, function(count) {
        log.info('deleted %d %s features', count, source.id);
        callback();
      });
    }, function() {
      fs.remove(cacheDir, function() {
        done();
      });
    });
  });

  after(function(done) {
    async.eachSeries([rivers], function(source, callback) {
      FeatureModel.deleteFeaturesBySourceId(source.id, function(count) {
        log.info('deleted %d %s features', count, source.id);
        callback();
      });
    }, function() {
      fs.remove(cacheDir, function() {
        done();
      });
    });
  });

  it ('should construct a cache with an error because there is no map', function(done) {
    var c = new Cache({
      outputDirectory: cacheDir,
      id: 'cache-test',
      name: 'cache-test',
      minZoom: 0,
      maxZoom: 1,
      geometry: turf.polygon([[
        [-180, -85],
        [-180, 85],
        [180, 85],
        [180, -85],
        [-180, -85]
      ]]),
      cacheCreationParams: {
        noGeoPackageIndex: true
      }
    });
    c.callbackWhenInitialized(function() {
      should.exist(c.error);
      done();
    });
  });

  it ('should construct a cache from a map that has already been initialized', function(done) {
    var mapObj = new Map(map);
    mapObj.callbackWhenInitialized(function() {
      cache = new Cache({
        source: mapObj,
        outputDirectory: cacheDir,
        id: 'cache-test',
        name: 'cache-test',
        minZoom: 0,
        maxZoom: 1,
        geometry: turf.polygon([[
          [-180, -85],
          [-180, 85],
          [180, 85],
          [180, -85],
          [-180, -85]
        ]]),
        cacheCreationParams: {
          noGeoPackageIndex: true
        }
      });
      cache.callbackWhenInitialized(function() {
        should.not.exist(cache.error);
        done();
      });
    });
  });

  it('should construct a cache from all the sources', function (done) {
    // this.timeout(0);
    cache = new Cache(cacheModel);
    cache.callbackWhenInitialized(function(err) {
      console.log('called back in construct a cache from all the sources');
      console.log(err);
      // log.info('Cache was initialized', JSON.stringify(newCache.cache.source.source.properties, null, 2));
      // newCache.cache.getTile.should.be.a.Function;
      done(err);
    });
  });

  it('should pull the 0/0/0 tile from the cache', function (done) {
    // this.timeout(0);
    cache.getTile('png', 0, 0, 0, function(err, tileStream) {
      should.exist(tileStream);
      var ws = fs.createOutputStream('/tmp/cache_test.png');
      tileStream.pipe(ws);
      ws.on('finish', function() {
        done(err);
      });
    });
  });

  it('should pull the 0/0/0 tile from the cache with no callback', function (done) {
    // this.timeout(0);
    cache.getTile('png', 0, 0, 0);
    done();
  });

  it ('should fail to pull a tile because the cache had an error', function(done) {
    var c = new Cache({
      outputDirectory: cacheDir,
      id: 'cache-test',
      name: 'cache-test',
      minZoom: 0,
      maxZoom: 1,
      geometry: turf.polygon([[
        [-180, -85],
        [-180, 85],
        [180, 85],
        [180, -85],
        [-180, -85]
      ]]),
      cacheCreationParams: {
        noGeoPackageIndex: true
      }
    });
    c.callbackWhenInitialized(function() {
      should.exist(c.error);
      c.getTile('png', 0, 0, 0, function(err, tileStream) {
        should.exist(err);
        should.not.exist(tileStream);
        done();
      });
    });
  });

  it ('should create a duplicate cache to test features already being in postgis', function(done) {
    var c = new Cache(cacheModel);
    c.callbackWhenInitialized(function() {
      should.not.exist(cache.error);
      done();
    });
  });

  describe('cache creation', function() {
    after(function(done){
      log.info('copy over the leaflet page to ', path.join(cacheDir, cacheModel.id, 'index.html'));
      fs.copy(path.join(__dirname, './leaflet/index.html'), path.join(cacheDir, cacheModel.id, 'index.html'), done);
    });

    before(function(done) {
      log.info('Deleting old GeoPackage cache');
      fs.remove(path.join(cacheDir, cacheModel.id, 'gpkg', cacheModel.id+'.gpkg'), function(err) {
        done(err);
      });
    });

    it('should generate the XYZ format for the cache', function (done) {
      cache.generateFormat('xyz', function(err, cache) {
          console.log('cache finished with err?', err);
          console.log('cache completed', cache);
          done();
        },
        function(progress, callback) {
          console.log('cache progress', progress);
          callback(null, progress);
        }
      );
    });

    it('should generate the GeoPackage format for the cache', function (done) {
      this.timeout(10000);
      cache.generateFormat('geopackage', function(err, cache) {
          console.log('cache finished with err?', err);
          console.log('cache completed', cache);
          done();
        },
        function(progress, callback) {
          console.log('cache progress', progress);
          progress.formats.geopackage.percentComplete.should.not.be.above(100);
          callback(null, progress);
        }
      );
    });

  });

});
Exemplo n.º 23
0
    describe(dataSource.format + ' cache tests', function() {

      var map = {
        id: 'test-map',
        dataSources: [dataSource]
      };

      var cache = {
        id: 'test-cache',
        name: dataSource.id + ' test cache',
        geometry: turf.polygon([[
          [-179, -85],
          [-179, 85],
          [179, 85],
          [179, -85],
          [-179, -85]
        ]]),
        minZoom: 0,
        maxZoom: 2,
        source: map,
        outputDirectory: '/tmp'
      };

      var f;
      before(function(done) {
        beforeTest('Check ' + dataSource.format + ' for ability to be a cache');
        try {
          f = new Format({
            cache: cacheObj,
            outputDirectory:cache.outputDirectory
          });
        } catch (e) {
        }
        done();

      });

      it ('should run tests if available for source ' + dataSource.format, function() {
        if (!f) return;
        describe(dataSource.format + ' cache tests if available', function() {

          before(function(done) {
            beforeTest(dataSource.format + ' cache tests');
            this.timeout(30000);
            FeatureModel.deleteFeaturesBySourceId(dataSource.id, function(count) {
              log.info('deleted %d %s features', count, dataSource.id);
              var cacheObj = new Cache(cache);
              cacheObj.callbackWhenInitialized(function(err, cacheObj) {
                try {
                  f = new Format({
                    cache: cacheObj,
                    outputDirectory:cache.outputDirectory
                  });
                } catch (e) {
                }
                done();
              });
            });
          });

          after(function(done){
            afterTest(dataSource.format + ' cache tests');
            fs.remove(path.join(cache.outputDirectory, cache.id), function(err) {
              fs.remove(path.join(cache.outputDirectory, map.id), function(err) {
                FeatureModel.deleteFeaturesBySourceId(dataSource.id, function(count) {
                  log.info('deleted %d %s features', count, dataSource.id);
                  done();
                });
              });
            });
          });

          it('should pull the 0/0/0 tile for the cache', function(done) {
            startTest('should pull the 0/0/0 tile for the cache ' + dataSource.format);
            this.timeout(30000);
            f.getTile('png', 0, 0, 0, dataSource.params || {noCache: true}, function(err, stream) {
              if (err) {
                done(err);
                return;
              }

              should.exist(stream);

              var ws = fs.createOutputStream(path.join('/tmp', 'test_000_'+dataSource.id+'.png'));
              ws.on('close', function() {
                endTest('should pull the 0/0/0 tile for the cache ' + dataSource.format);
                done();
              });
              stream.pipe(ws);

            });
          });

          it.skip('should pull the 0/0/0 geojson tile for the cache if there is one', function(done) {
            this.timeout(30000);
            f.getTile('geojson', 0, 0, 0, {noCache: true, projection: 4326}, function(err, stream) {
              if (err) {
                done(err);
                return;
              }
              if (dataSource.testParams && dataSource.testParams.featureCount) {
                should.exist(stream);
                var ws = fs.createOutputStream(path.join('/tmp', 'test_000_'+dataSource.id+'.geojson'));
                ws.on('close', function() {
                  done();
                });
                stream.pipe(ws);
              } else {
                should.not.exist(stream);
                done();
              }
            });
          });

            it('should generate the cache', function(done) {
              startTest('Generate the cache ' + dataSource.format);
              this.timeout(30000);
              f.generateCache(function(err, cacheObj) {
                var cache = cacheObj.cache;
                should.exist(cache.formats);
                should.exist(cache.formats[dataSource.format]);
                should.exist(cache.formats[dataSource.format].size);
                endTest('Generate the cache ' + dataSource.format);
                done();
              }, function(cache, callback) {
                callback(null, cache);
              })
            });

            it('should pull features for the cache', function(done) {
              startTest('Pull features for the cache ' + dataSource.format);
              this.timeout(30000);
              f.generateCache(function(err, cache) {
                f.getDataWithin(-180, -85, 180, 85, 4326, function(err, features) {
                  if (err) {
                    done(err);
                    return;
                  }
                  features.length.should.equal(dataSource.testParams.featureCount);
                  endTest('Pull features for the cache ' + dataSource.format);
                  done();
                });
              });
            });

            it('should generate the cache then download the format', function(done) {
              startTest('Generate the cache then download the format ' + dataSource.format);
              this.timeout(30000);
              f.generateCache(function(err, cache) {
                cache = cache.cache;
                f.getData(cache.minZoom, cache.maxZoom, function(err, status) {
                  if (status.noData) return done();

                  should.exist(status.stream);

                  var ws = fs.createOutputStream(path.join('/tmp', 'export_'+dataSource.id+status.extension));
                  ws.on('close', function() {
                    endTest('Generate the cache then download the format ' + dataSource.format);
                    done();
                  });
                  status.stream.pipe(ws);
                });
              }, function(cache, callback) {
                callback(null, cache);
              })
            });
            it('should generate the cache then delete the format', function(done) {
              startTest('Generate the cache then delete the format ' + dataSource.format);
              this.timeout(30000);
              f.generateCache(function(err, cache) {
                f.delete(function() {
                  endTest('Generate the cache then delete the format ' + dataSource.format);
                  done();
                });
              }, function(cache, callback) {
                callback(null, cache);
              })
            });
          });
      });
    });