2014-09-20 38 views
0

我的應用需要獲取路徑(經緯度列表)才能在地圖上顯示它。角度JS服務向控制器發送座標

我創建了一個可以執行所有api調用的基本控制器。

function mainController($scope, $http){ 

    $http.get('/api/lastrun') 
    .success(function(data){ 
     $scope.lastrun = data; 
    }) 
    .error(function(data){ 
     console.log('Error: ' + data); 
    }); 
} 

lastrun有一個路徑數組,讓您訪問每個位置。

我用角葉指令

function mapController($scope, positionService){ 
    angular.extend($scope, { 
       run: { 
        lat: 0.0, 
        lng: 0.0, 
        zoom: 4 
       }, 
       path: { 
        p1: { 
         color: 'red', 
         weight: 2, 
         latlngs: [ 
          { lat: 51.50, lng: -0.082 }, //here is an example of lat and lng in this controller 
          { lat: 48.83, lng: 2.37 }, 
          { lat: 0, lng: 7.723812 } 
         ] 
        } 
       } 
      }); 
} 

我想做的事情似乎很容易創建mapController。我只想將我獲得的職位數組放入我的mapController中,並在latlng中調用/ api/lastrun。

我不完全熟悉AngularJS中的服務,但我試圖建立我的(positionService)。但它沒有奏效。

有沒有人在這裏知道我可以繼續爲了創建與我的服務數組包含{lat:,lng:}列表並將其調用到我的mapController?

回答

0

我會做:

$scope.lastrun = []; 
$http.get('/api/lastrun') 
    .success(function(data){ 
     angular.forEach(data, function (value) { 
     $scope.lastrun.push({lat : value.lat, lng : value.lng}); 
     }); 
    } 
    }) 

然後:

path: { 
       p1: { 
        color: 'red', 
        weight: 2, 
        latlngs: $scope.lastrun 
       } 

希望這有助於

+0

我不會事情它的工作將作爲http請求和我將填寫的數組在兩個不同的控制器 – MaximeHeckel 2014-09-20 15:04:37

0

我終於找到了解決辦法。我在我的服務中使用了Adrien的解決方案,而不是在我的控制器中,然後將lastrunpos數組返回給我的mapController。這是我的代碼:

var selftracking = angular.module('selftracking',["leaflet-directive"]) 

    selftracking.service('positionService', function($http){ 
    var lastrunpos = []; 
    $http.get('/api/lastrun') 
     .success(function(data){ 
     angular.forEach(data.path, function (value) { 
     lastrunpos.push({lat : value.latitude, lng : value.longitude}); 
     }); 
    }); 
    return { 
     getPos : function() { 
      return lastrunpos; 
     } 
    } 
    }); 

function mainController($scope, $http){ 
    //Get all the last activities in the front page 
    $http.get('/api/lastactivity') 
    .success(function(data){ 
     $scope.lastactivity = data; 
    }) 
    .error(function(data){ 
     console.log('Error: '+ data); 
    }); 
    $http.get('/api/lastrun') 
    .success(function(data){ 
     $scope.lastrun = data; 
    }) 
    .error(function(data){ 
     console.log('Error: ' + data); 
    }); 
} 

function mapController($scope, positionService){ 
    angular.extend($scope, { 
       run: { 
        lat: 51.505, 
        lng: -0.09, 
        zoom: 4 
       }, 
       path: { 
        p1: { 
         color: 'red', 
         weight: 8, 
         latlngs: positionService.getPos() 
        } 
       } 
      }); 
}