artJSON.forEach(function(item){ if (item.location.string) { var realPoint = turf.point([item.location.gps_longitude,item.location.gps_latitude]) //Parse Test console.log("Geocoding: "+item.uid + " "+ item.location.string); var parseResult = Parser.parse(item.location.string); t.equal(item.location.distance,parseResult.distance,"Parsed correct distance "+parseResult.distance); var arr = Utils.splitTimeString(parseResult.time); var hour = parseInt(arr[0]); var min = parseInt(arr[1]); t.equal(item.location.hour,hour,"Correct hour "+hour); t.equal(item.location.minute,min,"Correct minute "+min); //Geocoding Test var point = coder.forward(item.location.string); t.ok(point,"Found point "+point.geometry.coordinates); var lat = point.geometry.coordinates[1]; var lon = point.geometry.coordinates[0]; t.ok(typeof lat == "number","Latitude is number"); t.ok(typeof lon == "number","Longitude is number"); var distance = turf.distance(point,realPoint); //t.ok(distance < .001, "Distance is close enough "+ (distance*1000.0) +" meters"); if (distance > .001) { var testError = {}; testError.id = item.uid; testError.locationString = item.location.string; testError.calculatedDistanceFeet = Math.round(Utils.milesToFeet(turf.distance(centerPoint,point,'miles'))); testError.theirDistanceFeet = Math.round(Utils.milesToFeet(turf.distance(centerPoint,realPoint,'miles'))); testError.ourBearing = turf.bearing(centerPoint,point).toFixed(2); testError.theirBearing = turf.bearing(centerPoint,realPoint).toFixed(2); testError.timeString = Utils.degreesToTime(testError.theirBearing,layout.bearing); ultraFailed.push(testError); } } else { console.log("Skipping Art: "+item.uid); } });
function(c) { //long, lat var startPoint = turf.point(target); var endPoint = turf.point([c["longitude"], c["latitude"]]); c.distance = turf.distance(startPoint, endPoint); });
turfMeta.featureEach(data, function(point) { // create a line from the waypoints if (prevPoint !== null) { var linestring = turf.lineString([ prevPoint.geometry.coordinates, point.geometry.coordinates ]); var duration = new Date(point.properties.time) - new Date(prevPoint.properties.time); duration /= 1000 * 60 * 60; // convert millisec to hours linestring.properties.length = roundFloat(turf.distance(prevPoint, point, 'kilometers'), 4); linestring.properties.speed = roundFloat(linestring.properties.length / duration); linestring.properties.bearing = roundFloat(turf.bearing(prevPoint, point), 1); linestring.properties.elevation = roundFloat(point.properties.ele - prevPoint.properties.ele); lines.push(linestring); // update global metadata result.meta.length += linestring.properties.length; result.meta.duration += duration; if (linestring.properties.speed <= 10) result.meta.standingtime += duration; if (result.meta.maxSpeed < linestring.properties.speed) result.meta.maxSpeed = linestring.properties.speed; linestring.properties.trackPosition = roundFloat(result.meta.length, 3); } prevPoint = point; });
function intersect(task, done) { console.log(++count + '/' + districts.length) var fpA = task.A.geojson.coordinates[0][0] var fpB = task.B.geojson.coordinates[0][0] if (fpA[0].length) fpA = fpA[0] if (fpB[0].length) fpB = fpB[0] var point1 = turf.point(fpA[0], fpA[1]) var point2 = turf.point(fpB[0], fpB[1]) turf.distance(point1, point2, 'miles', function(err, distance) { if (err) throw err if (distance > THRESHOLD) return setTimeout(done, 50) buffer(task.A.geojson, function(err, fcA) { if (err) return done(err) buffer(task.B.geojson, function(err, fcB) { if (err) return done(err) turf.intersect(fcA, fcB, function(err, fc) { if (err) return setTimeout(done, 50) var feature = fc.features[0] if (feature.geometries) feature = feature.geometries[0] if (!feature || feature.coordinates.length === 0) return setTimeout(done, 50) addIntersection(task.A, task.B, feature) console.log(task.A.DISTRICT, task.A.STATENAME, 'intersects with', task.B.DISTRICT, task.B.STATENAME) setTimeout(done, 50) }) }) }) }) }
distance: function(layers) { var points = [] for (var id in layers) { var layer = layers[id] if (layer.geojson) { if (layer.geojson.features) { var selected = _.where(layer.geojson.features, {selected: true}) selected.forEach(function(f) { if (f.geometry.type === 'Point') { points.push(f) } }) } if (layer.geojson.feature) { if (layer.geojson.feature.selected) { if (layer.geojson.feature.geometry.type === 'Point') { points.push(layer.geojson.feature) } } } } } var bearing = turf.distance(points[0], points[1], 'miles') var msg = '<p>Distance</p><p>' + numeral(bearing).format('0.0000') + ' mi' vex.dialog.alert(msg) },
reverseGeocoder.prototype.playaResult = function(point, polygon) { var bearing = turf.bearing(this.cityCenter,point); var time = utils.degreesToTime(bearing,this.cityBearing); var distance = turf.distance(point,this.cityCenter); var feet = utils.milesToFeet(distance); return time +" & "+ Math.round(feet) +'\' ' + polygon.properties.name; };
navigation.shouldReRoute = function(user, route) { var r = { type: 'Feature', properties: {}, geometry: route.routes[0].geometry }; var closestPoint = turf.pointOnLine(r, user); return turf.distance(user, closestPoint, defaults.units) > defaults.maxDistance ? true : false; };
test('distance', function (t) { for (var i = 0; i < points.length - 1; i++) { var expected = turf.distance(turf.point(points[i]), turf.point(points[i + 1])); var actual = ruler.distance(points[i], points[i + 1]); assertErr(t, expected, actual, 0.003, 'distance'); } t.pass('distance within 0.3%'); t.end(); });
feature.geometry.coordinates[0].forEach(function(coord){ var distance = turf.distance(center, turf.point(coord)); if(!closest || distance < closest){ closest = distance; _closest = feature; } });
chunk.forEach(pt => { if (points.length == 0) { points.push(pt); } else { let distance = turf.distance(pt, points[points.length-1], 'meters'); if (distance < max_distance) { points.push(pt); } } });
turfMeta.featureEach(data, function(point) { // create a line from the waypoints if (prevPoint !== null) { var duration = new Date(point.properties.time) - new Date(prevPoint.properties.time); duration /= 1000 * 60 * 60; // convert millisec to hours var sectionDist = turf.distance(prevPoint, point, 'kilometers'); distance += sectionDist; result.push({ timestamp: point.properties.time, speed: sectionDist / duration, distance: distance }); } prevPoint = point; });
request(dataUrl2, function (error2, response2, body2) { if (!error2 && response2.statusCode == 200) { //console.log('Data Set 1'); var parsed1 = parse.parse(body1); var goldenSpike1 = extractGoldenSpike(parsed1.data); //var pentagon1 = extractPentagon(parsed1.data); //console.log('Data Set 2'); var parsed2 = parse.parse(body2); var goldenSpike2 = extractGoldenSpike(parsed2.data); //var pentagon2 = extractPentagon(parsed2.data); var translation = turf.distance(goldenSpike1, goldenSpike2, 'miles'); console.log('Golden spike offset ' + translation + ' miles'); console.log('Golden spike lat delt: ' + (goldenSpike2.geometry.coordinates[1] - goldenSpike1.geometry.coordinates[1])); console.log('Golden spike lon delt: ' + (goldenSpike2.geometry.coordinates[0] - goldenSpike1.geometry.coordinates[0])); } });
jsonfile.readFile(input_file, function(err, data) { console.log('Loaded tracts'); var manhattan_center = { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [-74.005416, 40.721926] } }; var new_data = JSON.parse(JSON.stringify(data)); for (tract_index in data.features) { var feature = data.features[tract_index] var properties = feature.properties; var properties_new = {"S":properties["STATEFP10"], "L":properties["LOCALNAME"],"C":properties["TRACTCE10"],"H":properties["HH_COUNT"]}; new_data.features[tract_index].properties = properties_new; } var rem_data = JSON.parse(JSON.stringify(new_data)); rem_data.features = []; for (tract_index in new_data.features) { var feature = new_data.features[tract_index] var centroid = turf.centroid(feature); //console.log(feature); console.log(centroid.geometry.coordinates); var distance = turf.distance(centroid, manhattan_center, "miles"); //console.log(distance); if (distance < 20.0) { rem_data.features.push(feature); } } jsonfile.writeFile('everything_node.geojson', rem_data, {spaces: 2}, function(err) { console.error(err); }); });
/* * Takes a feature collection and creates a bounding box that contains all of * the features, auto-calculates an appropriate cell width based on the width * of the box, then turns creates a hexgrid. */ function create_hexgrids(json) { // Create the bounding box using features from both the download and upload // throughput data. var updown = turf.featurecollection(json.download.features.concat(json.upload.features)); // The combined up/down features will be used to add a map layer with a // scatter plot of all the data points. fs.writeFileSync(dirs.geojson + sub_dir + '-plot.json', JSON.stringify(updown)); var bbox = turf.extent(updown); var bbox_poly = turf.bboxPolygon(bbox); var point1 = turf.point(bbox_poly.geometry.coordinates[0][0]); var point2 = turf.point(bbox_poly.geometry.coordinates[0][1]); var distance = turf.distance(point1, point2, 'miles'); var hexgrids = { low : turf.hex(bbox, cell_widths.low, 'miles'), medium : turf.hex(bbox, cell_widths.medium, 'miles'), high : turf.hex(bbox, cell_widths.high, 'miles'), } return hexgrids; }
navigation.findClosestStepToUser = function(user, route) { var lowest = Infinity; var step = 0; for (var i = 0; i < route.routes[0].steps.length; i++) { var stepPoint = { type: 'Feature', properties: {}, geometry: { type: 'Point', coordinates: route.routes[0].steps[i].maneuver.location.coordinates } }; var distance = turf.distance(user, stepPoint, defaults.units); if (distance < lowest) { lowest = distance; step = i; } }; return step; };
function inRange(coord1, coord2) { var distance = turf.distance(turf.point(coord1), turf.point(coord2), 'miles') if(distance < 0.3) return true }
function distance_in_km (location1, location2) { var point1 = turf.point(location1.longitude, location1.latitude); var point2 = turf.point(location2.longitude, location2.latitude); return turf.distance(point1, point2, 'kilometers'); }
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); }); });
jsonfile.readFile(input_file, function(err, data) { console.log('Loaded tracts'); 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; } console.log("Length of tracts array: "+data.features.length); var generate = true; //generate = false; if (generate) { console.log("Calculating centroids"); var tract_index = 0; for (tract_index = 0; tract_index < data.features.length; tract_index++) { var turf_centroid = turf.centroid(turf_polygons[tract_index]); //var tract_area = turf.area(turf_polygons[tract_index]); tract_centroids[tract_index] = turf_centroid; } console.log("Calculating neighbors"); var last_pct = 0; var pct = 0; for (tract_index = 0; tract_index < data.features.length; tract_index++) { var centroid = tract_centroids[tract_index]; for (tcc = 0; tcc < data.features.length; tcc++) { var lc = turf_polygons[tcc]; var cc = tract_centroids[tcc]; var td = 100; if (tcc != tract_index) { td = turf.distance(centroid, cc, 'miles'); } if (tcc == tract_index || td <= 0.75) { if (!(tract_index in tract_nearby)) { tract_nearby[tract_index] = [tcc]; } else { tract_nearby[tract_index].push(tcc); } } } pct = (100.0*tract_index/data.features.length) if (pct - last_pct > 1) { console.log(pct.toString() + "% done"); last_pct = pct; } } jsonfile.writeFile('tract_nearby_node.json', tract_nearby, {spaces: 2}, function(err) { console.error(err); }); } });