简体   繁体   中英

$http angularJS loop for each object with leaflet issue

I'm making a little app for AngularJS personal training, and i'm getting a few errors.

I receive Json data from an API, and then I want to display amarker for every object I get. The problem is that I have a console error, so I supposed I've made a mistake.

Here goes my controller

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

      angular.extend($scope, {
          osloCenter: {},
          markers: {},
          defaults: {
              scrollWheelZoom: false
          }
      });


      $http.get('https://api.jcdecaux.com/vls/v1/stations?contract=toulouse&apiKey=*********************************').success(function(data) {

          $scope.bornes = data;

          for (var i = 0; i < data.length; i++) {

              $scope.markers.osloMarker = {
                  lat: data[i].position.lat,
                  lng: data[i].position.lng,
                  message: data[i].name,
                  focus: true,
                  draggable: false
              };
              $scope.osloCenter = {
                  lat: data[1].position.lat,
                  lng: data[1].position.lng,
                  zoom: 15
              };
          }

          console.log(data.position.lat);
          console.log(data.position.lng);
      });
  }]);

In my map I only have a marker for my last object. And in the console I have "TypeError: Cannot read property 'lat' of undefined"

When I try to display all my object outside of the map, in a list with ng-repeat, I have no problem.

Here go my HTML :

<div ng-controller="toulouseVeloListCtrl">
    <leaflet markers="markers" center="osloCenter" style="width: 100%; height: 500px;"></leaflet>
</div>

Any idea of what is wrong ?

Thank you a lot !!


I guess that problem is:

console.log(data.position.lat); 

Maybe you should use :

console.log(data[i].position.lat);

And also:

$scope.markers=[];
$scope.osloCenter=[];
for (var i = 0; i < data.length; i++) {

          $scope.markers[i].osloMarker = {
              lat: data[i].position.lat,
              lng: data[i].position.lng,
              message: data[i].name,
              focus: true,
              draggable: false
          };
          $scope.osloCenter[i] = {
              lat: data[1].position.lat,
              lng: data[1].position.lng,
              zoom: 15
          };
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM