Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as functions from 'firebase-functions';
- import * as turf from '@turf/turf'
- import { database, initializeApp } from 'firebase-admin';
- import * as admin from 'firebase-admin'
- import * as firebasedatabase from '@firebase/database'
- import { FirebaseDatabase } from '@firebase/database-types';
- import { ChildrenNode } from '@firebase/database/dist/src/core/snap/ChildrenNode';
- import { querystring } from '@firebase/util';
- import { QueryDocumentSnapshot } from '@google-cloud/firestore';
- import { GeoJSONObject, geojsonType, featureCollection, feature, geometry } from '@turf/turf';
- import { ref } from 'firebase-functions/lib/providers/database';
- import { json } from 'body-parser';
- export const onSensorUpdate = functions.database
- .ref('/Sensori/{sensorId}/feeds/{monthId}/{dayId}/{hourId}/{feedId}/')
- .onUpdate((change, context) => {
- const before = change.before.val()
- const after = change.after.val()
- if (before.field02 + 3 === after.field02) {
- console.log("il campo è stato già aggiornato")
- return null
- }
- const newval = average2(after.field02)
- const timeEdited = Date.now()
- return change.after.ref.update({ field02: newval })
- })
- export const onUserAuthentication = functions.auth
- .user().onCreate((user) => {
- const admin = require('firebase-admin');
- admin.initializeApp(functions.config().firebase)
- var db = admin.database().ref('Users')
- db.child(user.uid + '/type/').set("Citizien");
- db.child(user.uid + '/areas/').set("area1");
- console.log(user.uid);
- return 0
- })
- export const onZoneCreate = functions.database
- .ref('/Zones/Areas/{CAP}/{IDzona}')
- .onCreate((snapshot, context) => {
- const cap: string = context.params.CAP
- const IDZona: string = context.params.IDzona
- console.log('new zone (id Zona:' + IDZona + ') from CAP ' + cap)
- const feature = snapshot.val();
- const vettoreCoordinatePoligono: number[][][] = feature.geometry.coordinates
- console.log("VettoreCorordinate" + vettoreCoordinatePoligono);
- var ref = snapshot.ref
- var root = ref.root
- var poly = turf.helpers.polygon(vettoreCoordinatePoligono, { name: 'poly1' })
- console.log(poly)
- console.log(poly.geometry)
- console.log(poly.geometry.coordinates)
- var risultato = getSquareDivisionTurf(poly.geometry, 0.01); //0.01 = 1km
- //TO-DO : set FeatureCollection come segue,e poi nel campo features metterci tutte le feature da visualizzare
- var featureCollection = [{
- type: "FeatureCollection",
- //In features vanno tutti i record che vanno presi nel nodo /cap/idzona (e questo sarà un vettore )
- features: [{/*risultatozona1*/ }, {/*risultatozona2*/ }],
- properties: {
- }
- }]
- //INIZIALIZZAZIONE DELLA SEZIONE DATI PER LA NUOVA ZONA INSERITA
- var initializeZoneData = {
- feeds: 0,
- private: {
- averageH: {
- no2: 0,
- pm1: 0,
- pm10: 0,
- pm2_5: 0,
- pressione: 0,
- temperatura: 0,
- umidità: 0,
- voc: 0
- },
- lastFeeds: {
- last: 0
- }
- },
- public: {
- averageD: {
- no2: 0,
- pm1: 0,
- pm10: 0,
- pm2_5: 0,
- pressione: 0,
- temperatura: 0,
- umidità: 0,
- voc: 0
- }
- }
- }
- root.child('ZoneData/Areas/' + cap + '/' + IDZona).set(initializeZoneData)
- return root.child('Zones/AreasKM/' + cap + "/" + IDZona).set(risultato).then(() => {
- console.log('Write succeeded!');
- console.log(risultato)
- });
- })
- export const onZoneKMCreate = functions.database
- .ref("Zones/AreasKM/{CAP}/{IDzona}/{IDBBox}")
- .onCreate((snapshot, context) => {
- const cap: string = context.params.CAP
- const IDZona: string = context.params.IDzona
- const IDBBox: string = context.params.IDBBox
- const root = snapshot.ref.root
- var initializeZoneData = {
- feeds: 0,
- private: {
- averageH: {
- no2: 0,
- pm1: 0,
- pm10: 0,
- pm2_5: 0,
- pressione: 0,
- temperatura: 0,
- umidità: 0,
- voc: 0
- },
- lastFeeds: {
- last: 0
- }
- },
- public: {
- averageD: {
- no2: 0,
- pm1: 0,
- pm10: 0,
- pm2_5: 0,
- pressione: 0,
- temperatura: 0,
- umidità: 0,
- voc: 0
- }
- }
- }
- var vectorBBox: any = snapshot.val
- return root.child('ZoneData/AreasKM/' + cap + '/' + IDZona + '/' + IDBBox).set(initializeZoneData)
- })
- export const provaForEach = functions.database
- .ref('provaForEach/Eventi/{eventId}')
- .onCreate((snapshot, context) => {
- var refParent = snapshot.ref.parent.parent
- var refUsers = refParent.child('Users')
- var path: database.Reference
- var query = refUsers.once('value', function (usersSnapshot) {
- usersSnapshot.forEach(function (child) {
- if (child.val().cognome == "Tela") {
- console.log(child.key, child.val())
- child.ref.root.child("provaForEach").child(child.val().nome).set("Ok")
- return true
- }
- return false
- })
- })
- return refParent.child("Risultato").set("risultato")
- })
- //________________________________FUNZIONE ONSENSORCREATE_____________________________________________
- export const onFeedCreate = functions.database
- .ref('/Sensori/{sensorId}/feeds/{monthId}/{dayId}/{hourId}/{feedId}/')
- .onCreate((snapshot, context) => {
- //const structure=context.params.Header.Structure
- const feedId: string = context.params.monthId + context.params.dayId + context.params.hourId + context.params.feedId
- const sensorId = context.params.sensorId
- console.log('new feed (id Feed:' + feedId + ') from' + sensorId)
- //PRELEVO VALORI DEL FEED APPENA ARRIVATO
- const feed = snapshot.val()
- //INIZIALIZZAZIONE DEI REFERENCE UTILI AL DATABASE (areas, areasKM)
- var ref = snapshot.ref,
- root = ref.root,
- zoneRef = root.child('Zones'),
- areas = zoneRef.child('Areas'),
- areasKM = zoneRef.child('AreasKM')
- //PRELEVO LNG E LAT PER ISTANZIARE IL PUNTO
- var latitude = feed.latitude
- var longitude = feed.longitude
- var lnglat: number[] = [longitude, latitude]
- //CHIAMO LA FUNZIONE CHE ESEGUE LA RICERCA DEL PUNTO NELLE ZONE CHE NE AGGIORNERA' ANCHE LE MEDIE
- updateAverages(areas, lnglat, feed, context)
- //CHIAMO LA FUNZIONE CHE ESEGUE LA RICERCA DEL PUNTO NELLE ZONE A KM QUADRATO CHE NE AGGIORNERA' ANCHE LE MEDIE
- // var pathAreaKM = getPathAreasKM(areasKM, lnglat)
- var lastFeedAdded = {
- date: feedId,
- areasKM: areasKM.key,
- sensor: sensorId
- }
- return root.ref.child('LastUpdate').set(lastFeedAdded)
- })
- //_____________________________________________________________________
- //_____________________FUNZIONI UTILITARIE_____________________________
- //_____________________________________________________________________
- //QUESTA è LA FUNZIONE CHE AGGIORNA LE MEDIE, PRENDE COME PARAMETRI:
- // 1)il riferimento al nodo dove sono contenute le aree;
- // 2)long e lat del punto, per effettuare il controllo;
- // 3)il context del nuovo feed
- //Questa funzione richiama:
- // 'updateDataNodeZone' -> aggiorna le medie del Poligono
- // '
- function updateAverages(areas: database.Reference, lnglat: number[], feed: any, context: functions.EventContext): void {
- //turf.booleanPointInPolygon(polygonCenterTurf(llbPolygon), polygon)
- var path: database.Reference
- var point = turf.point(lnglat)
- const monthID = context.params.monthId
- const dayID = context.params.dayId
- const hourID = context.params.hourId
- const feedID = context.params.feedId
- const sensorId = context.params.sensorId
- var query = areas.once('value', function (areasSnapshot) {
- areasSnapshot.forEach(
- function (childCapSnapshot) {
- var flag = childCapSnapshot.forEach(
- function (childZoneSnapshot) {
- const vettoreCoordinatePoligono: number[][][] = childZoneSnapshot.val().geometry.coordinates
- var polygon = turf.polygon(vettoreCoordinatePoligono)
- if (turf.booleanPointInPolygon(point, polygon)) {
- path = childZoneSnapshot.ref
- updateDataNodeZone(path, feed, context)
- searchSquarePolygon(path, lnglat, feed, context)
- return true
- }
- return false
- })
- if (flag == false) {
- console.log("Record non corrispondente a nessun poligono.")
- areas.root.child("FeedsOutOfZones").push({ ID: sensorId + ": " + monthID + dayID + hourID + feedID })
- }
- return flag
- }
- )
- })
- }
- function searchSquarePolygon(zone: database.Reference, lnglat: number[], feed: any, context: functions.EventContext): void {
- var path: database.Reference
- var point = turf.point(lnglat)
- var zonekey = zone.key
- var capkey = zone.parent.key
- var zoneKM = zone.root.child('Zones').child('AreasKM').child(capkey).child(zonekey)
- const monthID = context.params.monthId
- const dayID = context.params.dayId
- const hourID = context.params.hourId
- const feedID = context.params.feedId
- const sensorId = context.params.sensorId
- console.log("ZoneKM:" + zoneKM.toString())
- zoneKM.once('value', function (childZoneSnapshot) {
- var flag = childZoneSnapshot.forEach(
- function (childSquareSnapshot) {
- const vettoreCoordinatePoligono: number[][][] = childSquareSnapshot.val().geometry.coordinates
- var polygon = turf.polygon(vettoreCoordinatePoligono)
- console.log(vettoreCoordinatePoligono)
- if (turf.booleanPointInPolygon(point, polygon)) {
- path = childSquareSnapshot.ref
- updateDataNodeZoneKM(path, feed, context)
- return true
- }
- return false
- })
- if (flag == false) {
- console.log("Record non corrispondente a nessun km quadrato.")
- zone.root.child("FeedsOutOfSquares").push({ ID: sensorId + ": " + monthID + dayID + hourID + feedID })
- }
- })
- }
- function updateDataNodeZoneKM(path: database.Reference, feed: any, context: functions.EventContext) {
- const squarekey = path.key
- const zonekey = path.parent.key
- const capkey = path.parent.parent.key
- const root = path.root
- const monthID = context.params.monthId
- const dayID = context.params.dayId
- const hourID = context.params.hourId
- const feedID = context.params.feedId
- const sensorId = context.params.sensorId
- var node: database.Reference = root.child('ZoneData').child('AreasKM').child(capkey).child(zonekey).child(squarekey)
- var feedsNode = node.child('feeds')
- var privateNode = node.child('private')
- var publicNode = node.child('public')
- feedsNode.push({ month: monthID, day: dayID, hour: hourID, feed: feed, sensor: sensorId, hour_day: hourID + dayID })
- //QUERY CHE AGGIORNA LA MEDIA GIORNALIERA
- var queryAverageD = publicNode.once('value', function (publicSnapshot) {
- var i = 0
- publicSnapshot.child('averageD').forEach(function (fieldSnapshot) {
- var fieldRef = fieldSnapshot.ref
- var fieldkey: string = fieldSnapshot.ref.key
- var val: number = fieldSnapshot.val()
- var newval = feed[fieldkey]
- if (val == 0) {
- fieldRef.set(newval)
- } else {
- feedsNode.orderByChild('day')
- .equalTo(dayID)
- .once('value', function (feedsNodeSnapshot) {
- var numFeedForDay = feedsNodeSnapshot.numChildren()
- var sum = 0
- feedsNodeSnapshot.forEach(function (feedIDSnapshot) {
- var x = feedIDSnapshot.val()
- sum = sum + x.feed[fieldkey]
- return false
- })
- var averageD = sum / numFeedForDay
- fieldRef.set((averageD))
- })
- }
- return false
- })
- })
- //QUERY CHE AGGIORNA LA MEDIA ORARIA
- var queryAverageH = privateNode.once('value', function (publicSnapshot) {
- var i = 0
- publicSnapshot.child('averageH').forEach(function (fieldSnapshot) {
- var fieldRef = fieldSnapshot.ref
- var fieldkey: string = fieldSnapshot.ref.key
- var val: number = fieldSnapshot.val()
- var newval = feed[fieldkey]
- if (val == 0) {
- fieldRef.set(newval)
- } else {
- feedsNode.orderByChild('hour_day')
- .equalTo(hourID + dayID)
- .once('value', function (feedsNodeSnapshot) {
- var numFeedForDay = feedsNodeSnapshot.numChildren()
- var sum = 0
- feedsNodeSnapshot.forEach(function (feedIDSnapshot) {
- var x = feedIDSnapshot.val()
- sum = sum + x.feed[fieldkey]
- return false
- })
- var averageD = sum / numFeedForDay
- fieldRef.set((averageD))
- })
- }
- return false
- })
- })
- }
- function updateDataNodeZone(path: database.Reference, feed: any, context: functions.EventContext) {
- const zonekey = path.key
- const capkey = path.parent.key
- const root = path.root
- const monthID = context.params.monthId
- const dayID = context.params.dayId
- const hourID = context.params.hourId
- const feedID = context.params.feedId
- const sensorId = context.params.sensorId
- var node: database.Reference = root.child('ZoneData').child('Areas').child(capkey).child(zonekey)
- var feedsNode = node.child('feeds')
- var privateNode = node.child('private')
- var publicNode = node.child('public')
- feedsNode.push({ month: monthID, day: dayID, hour: hourID, feed: feed, sensor: sensorId, hour_day: hourID + dayID })
- //QUERY CHE AGGIORNA LA MEDIA GIORNALIERA
- var queryAverageD = publicNode.once('value', function (publicSnapshot) {
- var i = 0
- publicSnapshot.child('averageD').forEach(function (fieldSnapshot) {
- var fieldRef = fieldSnapshot.ref
- var fieldkey: string = fieldSnapshot.ref.key
- var val: number = fieldSnapshot.val()
- var newval = feed[fieldkey]
- if (val == 0) {
- fieldRef.set(newval)
- } else {
- feedsNode.orderByChild('day')
- .equalTo(dayID)
- .once('value', function (feedsNodeSnapshot) {
- var numFeedForDay = feedsNodeSnapshot.numChildren()
- var sum = 0
- feedsNodeSnapshot.forEach(function (feedIDSnapshot) {
- var x = feedIDSnapshot.val()
- sum = sum + x.feed[fieldkey]
- return false
- })
- var averageD = sum / numFeedForDay
- fieldRef.set((averageD))
- })
- }
- return false
- })
- })
- //QUERY CHE AGGIORNA LA MEDIA ORARIA
- var queryAverageH = privateNode.once('value', function (publicSnapshot) {
- var i = 0
- publicSnapshot.child('averageH').forEach(function (fieldSnapshot) {
- var fieldRef = fieldSnapshot.ref
- var fieldkey: string = fieldSnapshot.ref.key
- var val: number = fieldSnapshot.val()
- var newval = feed[fieldkey]
- if (val == 0) {
- fieldRef.set(newval)
- } else {
- feedsNode.orderByChild('hour_day')
- .equalTo(hourID + dayID)
- .once('value', function (feedsNodeSnapshot) {
- var numFeedForDay = feedsNodeSnapshot.numChildren()
- var sum = 0
- feedsNodeSnapshot.forEach(function (feedIDSnapshot) {
- var x = feedIDSnapshot.val()
- sum = sum + x.feed[fieldkey]
- return false
- })
- var averageD = sum / numFeedForDay
- fieldRef.set((averageD))
- })
- }
- return false
- })
- })
- }
- // // ______________________FUNZIONI GEOMETRIA CON LIBRERIA TURF ___________________________________________________
- // //_______________________________________________________________________________________________________________
- function getSquareDivisionTurf(polygon: turf.Polygon, mq: number) {
- var bound = getBoundsRectangleTurf(polygon);
- var lowx: number,
- highx: number,
- lowy,
- highy,
- lats: number[] = [0],
- lngs: number[] = [0],
- vertices = polygon.coordinates[0],
- verticeslength: number = vertices.length
- for (var i = 0; i < verticeslength; i++) {
- lngs[i] = vertices[i][0];
- lats[i] = vertices[i][1];
- }
- lats.sort();
- lngs.sort();
- //VALORI VARIABILI
- lowx = +lngs[0].toFixed(2);
- highx = lowx + mq; //mq= 0.01 or 0.05
- lowy = +lats[0].toFixed(2);
- highy = lowy + mq; //mq= 0.01 or 0.05
- var startHighX = highx;
- var startLowX = lowx;
- var sw = turf.helpers.point([lowx, lowy]);
- var ne = turf.helpers.point([highx, highy]);
- var line = turf.lineString([sw.geometry.coordinates, ne.geometry.coordinates])
- var llb = turf.bbox(line);
- //Creo il poligono Di forma quadrata sul Bound quadrato llb
- var llbPolygon = turf.bboxPolygon(llb).geometry
- //calcolo il centro di del poligono di forma quadrata
- turf.centerOfMass
- var centro = polygonCenterTurf(llbPolygon) //DA SOSTITUIRE CON --> turf.centerOfMass
- //in realtà non uso questa variabile
- var x = 0;
- var y = 0;
- var i = 0;
- var elements = [];
- //DA SOSTITUIRE CON --> turf.centerOfMass
- //DA SOSTITUIRE CON --> turf.centerOfMass
- //DA SOSTITUIRE CON --> turf.centerOfMass
- //DA SOSTITUIRE CON --> turf.centerOfMass
- while (turf.booleanPointInPolygon(polygonCenterTurf(llbPolygon), bound)) {
- while (turf.booleanPointInPolygon(polygonCenterTurf(llbPolygon), bound)) {
- sw = turf.helpers.point([lowx, lowy]);
- ne = turf.helpers.point([highx, highy]);
- line = turf.lineString([sw.geometry.coordinates, ne.geometry.coordinates])
- llb = turf.bbox(line);
- llbPolygon = turf.bboxPolygon(llb).geometry
- var name = "X:" + x + " Y:" + y + "";
- if (turf.booleanPointInPolygon(polygonCenterTurf(llbPolygon), polygon)) {
- elements[i] =
- {
- type: "Feature",
- properties: {
- name: name
- },
- bbox: [llb[0], llb[1], llb[2], llb[3]], //left, bottom, right, top
- geometry: {
- type: "Polygon",
- coordinates: [
- [
- [llb[0], llb[1]],
- [llb[2], llb[1]],
- [llb[2], llb[3]],
- [llb[0], llb[3]],
- [llb[0], llb[1]],
- ]
- ]
- }
- };
- i++
- }
- highx = highx + mq; //aumento longitudine massima
- lowx = lowx + mq; //aumento latitudine massima
- x++;
- }
- //Resetto la longitudine a quella sul margine sinistro
- highx = startHighX;
- lowx = startLowX;
- //Incremento la latitudine
- highy = highy + mq;
- lowy = lowy + mq;
- //Istanzio il nuovo rettangolo al "piano" superiore in latitudine
- sw = turf.helpers.point([lowx, lowy]);
- ne = turf.helpers.point([highx, highy]);
- line = turf.lineString([sw.geometry.coordinates, ne.geometry.coordinates])
- llb = turf.bbox(line);
- llbPolygon = turf.bboxPolygon(llb).geometry
- y++;
- x = 0;
- }
- return elements;
- }
- function polygonCenterTurf(poly: turf.Polygon) {
- var lowx,
- highx,
- lowy,
- highy,
- lats: number[] = [0],
- lngs: number[] = [0],
- vertices = poly.coordinates[0]
- for (var i = 0; i < vertices.length; i++) {
- lngs[i] = vertices[i][0];
- lats[i] = vertices[i][1];
- }
- lats.sort();
- lngs.sort();
- lowx = lngs[0];
- highx = lngs[vertices.length - 1];
- lowy = lats[0];
- highy = lats[vertices.length - 1];
- var center_x: number = lowx + ((highx - lowx) / 2);
- var center_y: number = lowy + ((highy - lowy) / 2);
- var centerPoint = turf.helpers.point([center_x, center_y])
- return centerPoint
- }
- function getBoundsRectangleTurf(poly: turf.Polygon): turf.Polygon {
- var lowx: number,
- highx: number,
- lowy: number,
- highy: number,
- lats: number[] = [0],
- lngs: number[] = [0],
- vertices: number[][] = poly.coordinates[0]
- for (var i = 0; i < vertices.length; i++) {
- lngs[i] = vertices[i][0];
- lats[i] = vertices[i][1];
- }
- lats.sort();
- lngs.sort();
- lowy = lats[0];
- highy = lats[vertices.length - 1];
- lowx = lngs[0];
- highx = lngs[vertices.length - 1];
- var sw = turf.helpers.point([lowx, lowy]);
- var ne = turf.helpers.point([highx, highy]);
- var line = turf.lineString([sw.geometry.coordinates, ne.geometry.coordinates])
- var llb = turf.bbox(line);
- return turf.bboxPolygon(llb).geometry;
- }
- //__________________________________________________________________________________________________________________
- //___________________________FUNZIONI DI PROVA_________________________________________________
- function average2(val: string): number {
- let x: number
- x = +val;
- return x + 3
- }
- //_____________________________________________________________________________________________
- export const provaRequest = functions.https.onRequest((request, response) => {
- // i parametri vengono presi dalla form tipo così:
- // VENGONO PRESI PER IL CAMPO name__
- // ||
- // \/
- // <form action="https://us-central1-sensesquaredb.cloudfunctions.net/provaRequest" method = "post" id = "nameform" >
- // ||
- // \/
- // nome: <input type="text" name = "nome" > <br>
- // cognome: <input type="text" name = "cognome" > <br>
- // </form>
- var nome = request.body.nome // <- accendo al campo con "name"="nome"
- var cognome = request.body.cognome // <- accendo al campo con "name"="cognome"
- var stringa = [nome, cognome]
- console.log(nome + cognome)
- response.set('Access-Control-Allow-Origin', "*")
- response.set('Access-Control-Allow-Methods', 'POST')
- response.end(JSON.stringify({
- stringa
- }))
- })
- //___________________________________________________________________________________
- //__________________________richieste HTTP___________________________________________
- export const getAreasBoughtFromUid = functions.https.onRequest((request, response) => {
- //var uid= request.body.uid
- //VALORI DI PROVA
- var uid = 'XijVJNa0U1YNoZDY9JTecABgMHq1'
- response.set('Access-Control-Allow-Origin', "*")
- response.set('Access-Control-Allow-Methods', 'POST')
- const app = admin.initializeApp(functions.config().firebase)
- areasJsonResponse(response, uid, app)
- })
- function areasJsonResponse(response: functions.Response, uid: string, app: admin.app.App) {
- var rootRef = admin.database().ref()
- var nodeUsers = rootRef.child('Users')
- nodeUsers.child(uid).on('value', function (nodeUserSnapshot) {
- var nodeUserVal = nodeUserSnapshot.val()
- console.log("a: " + nodeUserVal)
- if (nodeUserVal['type'] == 'A') { //Tipo A = cittadino
- //TO-DO il client deve controllare se è stato mandato il flag
- //per controllare se è un cittadino e non un cliente
- var flagValue = { "0": "" }
- response.end(flagValue)
- }
- if (nodeUserVal['type'] == 'B') { //Tipo B = cliente pagante
- var areas: any[] = []
- nodeUserSnapshot.ref.child('areas')
- .on('value', function (nodeAreasSnapshot) {
- var i: number = 0
- nodeAreasSnapshot.forEach(function (areaSnapshot) {
- areas[i] = areaSnapshot.val()
- i++
- return false
- })
- response.end(JSON.stringify({
- areas
- }))
- })
- }
- app.delete()
- })
- }
- export const polygonGeojsonRequest = functions.https.onRequest((request, response) => {
- var areas: any[] // = request.body.areas
- // VALORI DI PROVA
- areas = [{
- cap: 'CAP-20100',
- zone: 'ZONA-01'
- }, {
- cap: 'CAP-20100',
- zone: 'ZONA-02'
- },]
- response.set('Access-Control-Allow-Origin', "*")
- response.set('Access-Control-Allow-Methods', 'POST')
- const app = admin.initializeApp(functions.config().firebase)
- geoJsonResponse(response, areas, app)
- });
- function geoJsonResponse(response: functions.Response, areas: any[], app: admin.app.App) {
- var nodeZones = admin.database().ref('Zones')
- var nodeAreas = nodeZones.child('Areas')
- var i: number
- var jsonAreas: any[] = []
- var cap: string
- var zone: string
- nodeAreas.once('value', function (nodeAreasSnapshot) {
- for (i = 0; i < areas.length; i++) {
- cap = areas[i].cap
- zone = areas[i].zone
- var feature = nodeAreasSnapshot.val()[cap][zone]
- var jsonFeature = {
- geometry: feature.geometry,
- properties: feature.geometry,
- type: feature.type
- }
- jsonAreas[i] = jsonFeature
- }
- response.end(JSON.stringify({
- type: "FeatureCollection",
- features: jsonAreas
- }))
- app.delete()
- })
- }
- //_____________________________________________________________________________________
- export const squaresGeojsonRequest = functions.https.onRequest((request, response) => {
- var areas: any[] // = request.body.areas
- // VALORI DI PROVA
- areas = [{
- cap: 'CAP-20100',
- zone: 'ZONA-01'
- }, {
- cap: 'CAP-20100',
- zone: 'ZONA-02'
- },]
- response.set('Access-Control-Allow-Origin', "*")
- response.set('Access-Control-Allow-Methods', 'POST')
- const app = admin.initializeApp(functions.config().firebase)
- squaresJsonResponse(response, areas, app)
- })
- function squaresJsonResponse(response: functions.Response, areas: any[], app: admin.app.App) {
- var nodeZones = admin.database().ref('Zones')
- var nodeAreasKM = nodeZones.child('AreasKM')
- var i: number
- var jsonAreas: any[] = []
- var cap: string
- var zone: string
- nodeAreasKM.once('value', function (nodeAreasKMSnapshot) {
- for (i = 0; i < areas.length; i++) {
- cap = areas[i].cap
- zone = areas[i].zone
- nodeAreasKM.child(cap).child(zone).on('value', function (nodeAreaKMSnapshot) {
- nodeAreaKMSnapshot.forEach(function (singleSquareSnapshot) {
- var feature = singleSquareSnapshot.val()
- var jsonFeature = {
- bbox: feature.bbox,
- geometry: feature.geometry,
- type: feature.type
- }
- jsonAreas.push(jsonFeature)
- return false
- })
- })
- }
- response.end(JSON.stringify({
- type: "FeatureCollection",
- features: jsonAreas
- }))
- app.delete()
- })
- }
- // function buildPaths(areasBought: any[]): string[] {
- // var zone = 'Zones/Areas'
- // var i: number
- // var refDatabaseString: string[] = []
- // for (i = 0; i < areasBought.length; i++) {
- // refDatabaseString[i] = zone + '/' + areasBought[i]['cap'] + "/" + areasBought[i]['zone']
- // }
- // return refDatabaseString
- // }
- // function geoJsonResponse(response: functions.Response, areasRef: database.Reference, zones: any[]) {
- // var i: number = 0
- // var jsonZones: string = undefined
- // areasRef.once('value', function (areasSnapshot) {
- // areasSnapshot.forEach(function (childCapSnapshot) {
- // if (i < zones.length) {
- // var queryCap = childCapSnapshot.ref
- // .orderByKey()
- // .equalTo(zones[i]['capkey'])
- // .once('value', function (childCapFoundSnapshot) {
- // childCapFoundSnapshot.forEach(function (childZoneSnapshot) {
- // childZoneSnapshot.ref
- // .orderByKey()
- // .equalTo(zones[i]['zonekey'])
- // })
- // })
- // } else
- // return true
- // i = i + 1
- // return false
- // })
- // })
- // for (i = 0; i < areas.length; i++) {
- // areas[i].once('value', function (childZoneSnapshot) {
- // if (jsonZones == undefined) {
- // jsonZones = childZoneSnapshot.val()
- // response.send(JSON.stringify(
- // jsonZones
- // ))
- // }
- // else
- // jsonZones = jsonZones + "," + childZoneSnapshot.val()
- // if (i == areas.length - 1) {
- // response.end(JSON.stringify({
- // jsonZones
- // }))
- // }
- // })
- // }
- // response.end(JSON.stringify({
- // geoJsonResponse
- // }))
- // }
- // function geoJsonResponse(zona: string[]): string[] {
- // var i: number
- // var zone = 'Zones/Areas/CAP-20100'
- // var ref: string[]=[]
- // for (i = 0; i < zona.length; i++) {
- // ref[i] = zone +'/'+ zona[i]
- // console.log('Sono nell if')
- // }
- // return ref
- // }
- function sleep(milliseconds) {
- var start = new Date().getTime();
- for (var i = 0; i < 1e7; i++) {
- if ((new Date().getTime() - start) > milliseconds) {
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement