-1

I need to order my execution. I need to make sure my COMPLETE coords() method finishes, once it is called. how to add a promise or $q to it? I tried printing on console and found forEach loop in coords is completed after the last line of coords() function is executed. see code below. I am really new to angular help please

var appa = angular.module('appa',['firebase','uiGmapgoogle-maps']);
appa.controller('mainCtrl', function($firebaseObject,$scope,$q) {

              $scope.coords = function(){
               
                var ref =  firebase.database().ref();
                var latArray = [];
                var lngArray = [];
                var cenlat;
                var cenlng;
                  var marker = [];
                ref.once("value")
                .then(function(snapshot)
                {
                snapshot.forEach(function(child)
                {

                  latArray.push(child.child("Lat").val());
                  console.log(child.child("Lat").val());
                  lngArray.push(child.child("Long").val());
                  var mark = {
                  id: child.child("Id").val(),
                  coords: {
                  latitude: child.child("Lat").val(),
                  longitude: child.child("Long").val()
                  },
                  options: { title: child.child("Alt").val() }
                  };
                  marker.push(mark);
CONSOLE.LOG("wWHY IS THIS PRINTED aFTER??? AND HOW TO HANDLE THIS ??");
                });

                   cenlat = (Math.max.apply(Math,latArray)+Math.min.apply(Math,latArray)/2);
                   cenlng = (Math.max.apply(Math,lngArray)+Math.min.apply(Math,lngArray)/2);

                });
                $scope.map.center.latitude = cenlat;
                $scope.map.center.longitude = cenlng;
CONSOLE.LOG("wWHY IS THIS PRINTED BEFORE??? AND HOW TO HANDLE THIS ??");
});
                };

              $scope.map = {
                center:
                {
                  latitude: 51,
                  longitude: 4
                         },
                 zoom: 2
                      };

      $scope.coords();
      


   });
nemo asad
  • 11
  • 4
  • 1
    Did you notice the syntax error in the snippet? The code you posted is invalid javascript, you really should fix that and also post code that has proper formatting, as it stands, your code is more difficult to read, surely that isn't exactly how you write your code?!? And **CONSOLE.LOG** will fail anyway, it's **console.log** - javascript is not visual basic, it's case sensitive – Jaromanda X Dec 11 '16 at 07:35
  • nemoAsad, you have done 95% of the debugging by gathering the evidence - the two messages are logged in the wrong order - so you know the timing of code execution. All you need to do is shuffle the code around such that the `$scope.map` statements execute at the right time. It's not complicated. – Roamer-1888 Dec 11 '16 at 11:28
  • Once that's fixed, there's more .... (1) Your average calcs appear to be wrong; you most likely want `(max + min)/2`, not `(max + min/2)`. (2) Remember that lat and lng range from -180 to +180. `(max + min)/2` is OK for any cluster of lats and for lngs spanning the Grenwich Meridian, but for lngs spanning the International Date Line, `(max + min)/2` will give an unexpected result (and it's not good enough to say "it will never happen" because one day it will!). (3) Simple arithmetic mean of max and min values favours outliers; consider a "centre of gravity" algorithm instead. – Roamer-1888 Dec 11 '16 at 11:37

1 Answers1

0

you are using firebase and can easily check the returned children storing them in a variable. and then decrement the variable in forEach loop.

//initialized var a, is having child count
a = snapshot.numChildren();

And the complete code below will create the ordered execution and has a a basic implementation of promise. I have added console.log to show the order as well. I hope it helps some how.

//complete code

var appa = angular.module('appa',['firebase','uiGmapgoogle-maps']);
appa.controller('mainCtrl', function($firebaseObject,$scope,$q){

              $scope.coords = function(){
var q = $q.defer();
                var ref =  firebase.database().ref();
                var latArray = [];
                var lngArray = [];
                var cenlat;
                var cenlng;
                var a="0";
                var marker = [];

                ref.once("value")
                .then(function(snapshot)
                {
               a = snapshot.numChildren();
                console.log(a);
                snapshot.forEach(function(child)
                {
                  latArray.push(child.child("Lat").val());
                  console.log(child.child("Lat").val());
                  lngArray.push(child.child("Long").val());
                  var mark = {
                  id: child.child("Id").val(),
                  coords: {
                  latitude: child.child("Lat").val(),
                  longitude: child.child("Long").val()
                  },
                  options: { title: child.child("Alt").val() }
                  };
                  a= a-1;
                  console.log("this is current"+a);
                  marker.push(mark);
                });
console.log("hi"+a);
console.log("going for cenlat"+cenlat);
            cenlat = (Math.max.apply(Math,latArray)+Math.min.apply(Math,latArray)/2);
console.log("done with cenlat"+cenlat);
console.log("going for cenlng"+cenlng);
            cenlng = (Math.max.apply(Math,lngArray)+Math.min.apply(Math,lngArray)/2);
console.log("done with cenlng"+cenlng);
            $scope.map.center.latitude = cenlat;
            $scope.map.center.longitude = cenlng;
            if(a==0){
            q.resolve('resolved');
            }
            else{
            q.reject('rejected');
            }
                });

                };
              $scope.map = {
                center:
                {
                  latitude: 51,
                  longitude: 4
                         },
                 zoom: 2
                      };

    $scope.coords().then(
        function(v){
console.log(v);
      },
    function(err){
console.log(err);
    });

   });
  • 1
    Please, at least fix the indentation! – Roamer-1888 Dec 11 '16 at 11:03
  • I know the OP asked for something to do with `$q` but it's not necessary. I guess the `if(a == 0) (...)` block above is supposed to demonstrate something, but *what* exactly!? In its current form it demonstrates nothing and does nothing except add a little to the next electricity bill. – Roamer-1888 Dec 11 '16 at 11:46