2016-04-21 34 views
0

我正在制作一个基于网站的仪表板。其中一项功能是显示所有客户的位置。当我将这些放置在地图上时,我似乎无法获得弹出权。javascript在内部函数中保持var

function getCoordinates(locationList) { 
      for (var i = 0; i < locationList.length; i++) { 
       if (locationList[i].city != null) { 
        $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token) 
         .success(
          function (data) { 
           var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap); 
           marker.bindPopup(locationList[i].customerName); 
          } 
         ); 
       } 
      } 
     } 

当我使用此代码的弹出窗口将只在每一个弹出up.does有人上一次客户的名字知道如何确保使用正确的用户的属性?

回答

0

这是一个关闭问题,要解决它,你必须将你的$ http调用移动到这样的新函数。

function httpCall(locationList,i){ 
     $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token) 
         .success(
          function (data) { 
           var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap); 
           marker.bindPopup(locationList[i].customerName); 
          } 
     ); 


} 
+0

thx。这对我有效。 – ziraak

0

fori总是locationList.length - 1。尝试添加本地的IIFE。例如,您可以通过替换for回路来解决问题locationList.forEach

0

这是一个范围问题。您的i已更新,稍后当您点击弹出窗口时,它会读取最后一个值i

你应该把你的conditionnal在for内搭在参数i功能:

function getCoordinates(locationList) { 
    for (var i = 0; i < locationList.length; i++) { 
    conditionnalGet(i); 
    } 
    function conditionnalGet(i) { 
    if (locationList[i].city != null) { 
     $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token) 
     .success(function (data) { 
      var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap); 
      marker.bindPopup(locationList[i].customerName); 
     }); 
    } 
    } 
} 
0

这是臭名昭著的循环问题。由于您只是定义了函数,并没有在for循环结束时实际执行它,所以所有函数的索引号为i的值都相同。

解决方案:是将值赋给变量并在成功回调中使用此变量。

for (var i = 0; i < locationList.length; i++) { 
    if (locationList[i].city != null) {  
    var currLocation = locationList[i]; // assign the data to a variable 
    $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token) 
    .success(
      function (data) { 
       var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap); 
       marker.bindPopup(currLocation.customerName); // use the variable instead of the indexed lookup 
      } 
      ); 
    } 
} 

让我知道这是否有帮助。