const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); // Listens for new messages added to /messages/:pushId/original and creates an // uppercase version of the message to /messages/:pushId/uppercase exports.takecurrdata = functions.database.ref('loc') .onUpdate((snapshot, context) => { // Grab the current value of what was written to the Realtime Database. var data = snapshot.after.val(); var latarray =snapshot.after.child('targetloc').child('lati').val(); var lonarray =snapshot.after.child('targetloc').child('longi').val(); console.log(latarray); console.log(snapshot.after.child('targetloc').val()); var ai=0; var d = 0; var smallest = 1000000; var last = latarray.length; admin.database().ref().child('count').set(parseFloat(last-1)) while(ai < last){ var lati = parseFloat(latarray[ai]); var longi = parseFloat(lonarray[ai]); console.log(lati); console.log(longi); var clati = parseFloat(snapshot.after.child('currloc').child('lati').val()); var clongi =parseFloat(snapshot.after.child('currloc').child('longi').val()); console.log(clati); console.log(clongi); const R = 6371e3; // metres const φ1 = lati * Math.PI/180; // φ, λ in radians const φ2 = clati * Math.PI/180; const Δφ = (clati-lati) * Math.PI/180; const Δλ = (clongi-longi) * Math.PI/180; const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) + Math.cos(φ1) * Math.cos(φ2) *Math.sin(Δλ/2) * Math.sin(Δλ/2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); d = R * c; // in metres if(d < smallest){ smallest =d; } if(ai === last - 1){ console.log(smallest); admin.database().ref().child('distance').set(parseFloat(smallest)); } ai++; } // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to the Firebase Realtime Database. // Setting an "uppercase" sibling in the Realtime Database returns a Promise. });