4
我正在開發一個angularJS應用程序,其中我的設備地理座標每隔幾秒就被髮送到我的REST服務。地理座標發送代碼位於一個控制器中。這意味着如果該控制器的模板頁面處於打開狀態,則僅在我的服務器中更新地理定位。我如何做到這一點,以便無論我在哪個頁面上都始終更新地理定位。如何使angularJS控制器始終處於活動狀態?
這是我對於控制器代碼:
.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);
}])
這是我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;
}]);
把這些代碼是一個服務,而不是在一個控制器。 –
我已更新我的代碼,請問我可以如何修改我的代碼? – Elisha512