2

I am facing trouble with my angularjs script.

Background: I am trying to determine the location of the user, I have written my business logic in my service from where I am returning the location of the user.

Problem : The result I am getting in my console is as below :

[undefined] landingPage.js:11 undefined landingPage.js:11 undefined

var app = angular.module("PublicEvents", ["geolocation"]);

app.controller("iterator", ["$scope", "$http", "locationService1", function($scope, $http, locationService1){
    $scope.targetCity = [];
    $scope.targetCity.push(locationService1.location());

    console.log($scope.targetCity);
    $scope.$watch(function () { return locationService1.cityNameArray; },
            function (value) {
        $scope.targetCity = value;
        console.log($scope.targerCity);
    }
    );

}]);



app.service("locationService1",['$http','$window', function( $http, $window){
    var access = this;
    this.location = function(){
        $window.navigator.geolocation.getCurrentPosition(function(position) {
            access.lat = position.coords.latitude;
            access.long = position.coords.longitude;

            access.locationData = [];
            access.cityNameArray = [];

            /*var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=18.9750,72.8258&sensor=true";*/
            var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+access.lat+","+access.long+"&sensor=true";

            //AJAX CALL TO GET THE LOCATION
            $http.get(url).then(function(response) {
                access.locationData = response.data; 
                if(access.locationData.status == "OK" || access.locationData.status==200 ) {
                    angular.forEach(access.locationData.results, function(value, key){
                        var len = value.address_components.length;
                        for(var i = 0; i< len; i++){
                            if(value.address_components[i].types[0] =="locality" || value.address_components[i].types[0] =="sublocality_level_1"){
                                access.cityNameArray.push(value.address_components[i].long_name);
                            }
                        }
                    }); 
                };
            }); 
            return access.cityNameArray;
        });
    };
}]);
5
  • what is line 11 in landingPage.js? Commented Sep 25, 2015 at 18:06
  • console.log($scope.targerCity); inside $watch Commented Sep 25, 2015 at 18:07
  • I think it might be a duplicate of this question then: stackoverflow.com/questions/25575963/… Commented Sep 25, 2015 at 18:09
  • angular will fire the watcher once when you create it and since nothing was returned from the server yet your value is undefined. Pankaj's answer seems pretty good too. :) Commented Sep 25, 2015 at 18:10
  • Let me check the link you have given.... Commented Sep 25, 2015 at 18:12

1 Answer 1

2

Seems like you need to return data from an async call and you are returning value from outside the function. I'd suggest you to use promise pattern in such situation.

this.location = function(){
    $window.navigator.geolocation.getCurrentPosition(function(position) {
        access.lat = position.coords.latitude;
        access.long = position.coords.longitude;

        access.locationData = [];
        access.cityNameArray = [];

        /*var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=18.9750,72.8258&sensor=true";*/
        var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+access.lat+","+access.long+"&sensor=true";

        //return promise from here..
        return $http.get(url).then(function(response) {
            access.locationData = response.data; 
            if(access.locationData.status == "OK" || access.locationData.status==200 ) {
                angular.forEach(access.locationData.results, function(value, key){
                    var len = value.address_components.length;
                    for(var i = 0; i< len; i++){
                        if(value.address_components[i].types[0] =="locality" || value.address_components[i].types[0] =="sublocality_level_1"){
                            access.cityNameArray.push(value.address_components[i].long_name);
                        }
                    }
                }); 
            };
            return access.cityNameArray; //returned from success callback
        }); 

    });
};

Inside controller you need to use .then function to get data from the service loacation function. You were doing console.log when you are doing async call which doesn't return anything.

locationService1.location().then(function(data){ //success callback.
   $scope.targetCity.push(data)
},function(error){ //error callback.
   console.log(error)
});
Sign up to request clarification or add additional context in comments.

5 Comments

I don't see any promise being returned from the location function.
@toskv Thanks for your heads up.. I editing my answer.. TYSM
Is it required to return access.cityNameArray and the promise...Actually I am getting an error cannot read property 'then' of undefined
@PragamShrivastava yes you need to return both return $http.get(url). and access.cityNameArray
It worked after I segregated the navigator function! Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.