не получает ссылку geoQuery на updateCriteria после выполнения geoFire.query в geofire - PullRequest
0 голосов
/ 01 ноября 2019

Я использую функцию firebase на стороне сервера и хочу реализовать геозону, используя geoFire на стороне сервера. для этого я создаю функцию, когда пользователь добавляет местоположение геозоны, как показано ниже кода ..

    exports.setGeofenceUsingGeoFire = functions.database
        .ref('/geo_place/0_myself/{user_id}')
        .onCreate((snap, context) => {

            const data = snap.val()

            var dd = Object.values(data)
            var afterData = dd[0];

            if (afterData == null)
                return true

            // get all variables
            const reducerId = afterData.reducer
            const mLatitude = afterData.mLatitude
            const mLongitude = afterData.mLongitude


            // set geofence and save into firebase DB 
            geoFire.set(reducerId, [mLatitude, mLongitude]).then(function () {
                console.log("Provided key " + reducerId + " has been added to GeoFire");
            }, function (error) {
                console.log("Error: " + error);
            });

            return false
        })

теперь, когда пользователь будет перемещаться, я получаю текущий lat и long пользователя внутри другой функции и запрашиваю geoFire, как указанониже ...

    // check geofence for user and notify them when they enter & exit 
   //region
    exports.checkGeofenceLocation = functions.database
        .ref('/location/{user_id}')
        .onWrite((snap, context) => {


            var userId = context.params.user_id;
            const data = snap.before.val();  
            var operation;

          //check if geoQuery exist or not in db and then create and 
         //updateCriteria.
         admin.database().ref(`server-geofire-query/${userId}`)
            .once('value')
            .then(function (result) {

                var data = result.val();

             // if geoFire query not created for this user id in  firebase DB else update 
                if (data == null || data == undefined || data == "") {

                    operation = "Creating";

                    geoQuery = geoFire.query({
                        center: [data.mLatitude, data.mLongitude],
                        radius: 10
                    });
                    geoQuery.on("key_entered", function (key, location, distance) {

                        console.log(key + " is located at [" + location + "] which is within the 
                       query (" + distance.toFixed(2) + " km from center)");
                    });

                    geoQuery.on("key_exited", function (key, location, distance) {

                        console.log(key + " is located at [" + location + "] which is no longer 
                        within the query (" + distance.toFixed(2) + " km from center)");
                    });

                    var obj = {
                        user_id: userId,
                        lat: data.mLatitude,
                        lon: data.mLongitude,
                        radius: 10,
                        timestamp: new Date().getTime(),
                        geoQuery: geoQuery.toString()
                    }
          // save the geo query into DB to get geoQuery ref next time 
          // to update geofire Criteria

                   admin.database().ref(`server-geofire-query/${userId}`).set(obj);

                } else {

                    var geoQueryString = data.geoQuery;
                    console.log("GEO QUERY STRING :: " + geoQueryString);
                    geoQueryString.replace(/['"]+/g, '')

                    geoQuery = geoQueryString

                    console.log("GEO QUERY :: " + geoQuery);

                    operation = "Updating";
         // here i am getting undefined value of geoQuery, if i don't put it on firebase DB
                    geoQuery.updateCriteria({
                        center: [lastNode.mLatitude, lastNode.mLongitude],
                        radius: RADIUS
                    });
                }

                console.log(operation + " the query: centered at [" + lastNode.mLatitude + "," + lastNode.mLongitude + "] with radius of " + RADIUS + "km")

            }); 




            return false;
        })

здесь мне нужно выполнить geoQuery.updateCriteria, чтобы можно было обновить конкретное местоположение пользователя. если я не сохраняю geoQuery, то получаю неопределенное в geoQuery ref. и если я помещаю ссылку geoQuery в базу данных firebase Db, как вы можете видеть в приведенном выше коде, то я не могу получить анализ ref (объект) geoQuery из базы данных для выполнения функции geoQuery.updateCriteria, чтобы она могла инициировать событие входа и выхода.

, пожалуйста, скажите мне, как сохранить объект geoQuery в базе данных Firebase и получить этот объект для обновления запроса.

любая помощь будет оценена. спасибо.

...