How to make angularJS controller active anytime?

I am developing an angularJS application where my geo-coordinates from a device are taken and sent to my REST service every few seconds. The code for sending geodata is located in only one controller. This means that geolocation is only updated on my server if the template page for this controller is open. How to make sure that geolocation is always updated no matter what page I'm on.

Here is my code for this controller:

.controller('geolocationCtrl', [ '$scope', '$http', 'geolocationFactory',
        function($scope, $http, geolocationFactory) {

            // constants should be uppercase
            var GET_PATH = 'https://temp-domain.co.uk/rest/rest.php/client/geolocation',
                PUT_PATH = 'https://temp-domain.co.uk/rest/rest.php/client/geolocation/update';


            $http.get(GET_PATH).then(function (response) {
                var respLong = Number(response.data.longitude),
                    respLat = Number(response.data.latitude);

                $scope.map = drawMap(respLong, respLat);
                $scope.marker = new google.maps.Marker({
                    position: new google.maps.LatLng(respLong, respLat)
                });
                $scope.marker.setMap($scope.map);

            }, function (errorResponse) {
                console.error('error response ' + errorResponse);
            });

            function drawMap(latitude, longitude) {
                var lat = latitude,
                    long = longitude,
                    currentLatlng = new google.maps.LatLng(lat, long);
                var map = new google.maps.Map(document.getElementById('map'), {
                    center: currentLatlng,
                    zoom: 10
                });
                return map;
            };

            setInterval(function () {
                geolocationFactory.getCurrentPosition().then(function(location) {

                    var newLatitude = location.coords.latitude,
                        newLongitude = location.coords.longitude;

                    // delete old marker
                    $scope.marker.setMap(null);
                    $scope.marker = new google.maps.Marker({
                        position: {
                            lat: newLatitude,
                            lng: newLongitude
                        }
                    });
                    var LatLng = new google.maps.LatLng(newLatitude, newLongitude);
                    $scope.map.setCenter(LatLng);
                    $scope.marker.setMap($scope.map);


                    // send data to server
                    $http.put(PUT_PATH, {
                        "longitude": newLatitude,
                        "latitude": newLongitude
                    }).then(function (response) {
                        console.log('data sended');
                    }, function (errorResponse) {
                        console.error(errorResponse);
                    });
                }.bind(this));

            }, 2000);

        }])

This is my service.js

angular.module('app.services', [])

.factory('BlankFactory', [function(){

}])

.service('BlankService', [function(){

}])
.factory('geolocationFactory', ['$window', '$rootScope', '$q', function ($window, $rootScope, $q) {

    function supported() {
        return 'geolocation' in $window.navigator;
    }

    var retVal = {
        getCurrentPosition: function (options) {
            var deferred = $q.defer();
            if (supported()) {
                $window.navigator.geolocation.getCurrentPosition(
                    function (position) {
                        $rootScope.$apply(function () {
                            this.coords = position.coords;
                            this.timestamp = position.timestamp;
                            deferred.resolve(position);
                        });
                    },
                    function (error) {
                        $rootScope.$apply(function () {
                            deferred.reject({error: error});
                        });
                    }, options);
            } else {
                deferred.reject({
                    error: {
                        code: 2,
                        message: 'This web browser does not support HTML5 Geolocation'
                    }
                });
            }
            return deferred.promise;
        },

        drawMarker: function (lat, lng) {

            map = new google.maps.Map(document.getElementById("map"), mapOptions);

            var marker = new google.maps.Marker({
                position: myLatlng,
                title: "Hello World!"
            });
        }
    };
    return retVal;
}]);
+4
source share
1 answer

. , , .

:

angular.module('app.services', [])

.factory('BlankFactory', [function(){

}])

.service('BlankService', [function(){

}])
.factory('geolocationFactory', ['$window', '$rootScope', '$q', '$interval', '$http', function ($window, $rootScope, $q, $interval, $http) {

    function supported() {
        return 'geolocation' in $window.navigator;
    }

    var retVal = {
        getCurrentPosition: function (options) {
            var deferred = $q.defer();
            if (supported()) {
                $window.navigator.geolocation.getCurrentPosition(
                    function (position) {
                        $rootScope.$apply(function () {
                            this.coords = position.coords;
                            this.timestamp = position.timestamp;
                            deferred.resolve(position);
                        });
                    },
                    function (error) {
                        $rootScope.$apply(function () {
                            deferred.reject({error: error});
                        });
                    }, options);
            } else {
                deferred.reject({
                    error: {
                        code: 2,
                        message: 'This web browser does not support HTML5 Geolocation'
                    }
                });
            }
            return deferred.promise;
        },

        drawMarker: function (lat, lng) {

            map = new google.maps.Map(document.getElementById("map"), mapOptions);

            var marker = new google.maps.Marker({
                position: myLatlng,
                title: "Hello World!"
            });
        }
    };


    // the factory service runs at startup, so the interval will run the whole time the app is running
    $interval(function () {
        retVal.getCurrentPosition().then(function(location) {

            var newLatitude = location.coords.latitude,
                newLongitude = location.coords.longitude;

            // broadcast event
            $rootScope.$broadcast('geolocationCurrentPosition', newLatitude, newLongitude);

            // send data to server
            $http.put(PUT_PATH, {
                "longitude": newLatitude,
                "latitude": newLongitude
            }).then(function (response) {
                console.log('data sended');
            }, function (errorResponse) {
                console.error(errorResponse);
            });
        }.bind(this));

    }, 2000);

    return retVal;
}]);

:

.controller('geolocationCtrl', [ '$scope', '$http',
    function($scope, $http) {

        // constants should be uppercase
        var GET_PATH = 'https://temp-domain.co.uk/rest/rest.php/client/geolocation',
            PUT_PATH = 'https://temp-domain.co.uk/rest/rest.php/client/geolocation/update';


        $http.get(GET_PATH).then(function (response) {
            var respLong = Number(response.data.longitude),
                respLat = Number(response.data.latitude);

            $scope.map = drawMap(respLong, respLat);
            $scope.marker = new google.maps.Marker({
                position: new google.maps.LatLng(respLong, respLat)
            });
            $scope.marker.setMap($scope.map);

        }, function (errorResponse) {
            console.error('error response ' + errorResponse);
        });

        function drawMap(latitude, longitude) {
            var lat = latitude,
                long = longitude,
                currentLatlng = new google.maps.LatLng(lat, long);
            var map = new google.maps.Map(document.getElementById('map'), {
                center: currentLatlng,
                zoom: 10
            });
            return map;
        };

        // listen for the event from geolocationFactory
        $scope.$on('geolocationCurrentPosition', function(event, latitude, longitude){
            // delete old marker
            $scope.marker.setMap(null);
            $scope.marker = new google.maps.Marker({
                position: {
                    lat: latitude,
                    lng: longitude
                }
            });
            var LatLng = new google.maps.LatLng(latitude, longitude);
            $scope.map.setCenter(LatLng);
            $scope.marker.setMap($scope.map);
        });
    }])
0

Source: https://habr.com/ru/post/1651888/


All Articles