2015-05-20 57 views
3

我正在使用他們的最後一個位置地址,名稱,時間等跟蹤多個設備的項目。要顯示地址,我使用反向地址解析(最後位置lat long來自mysql db )。代碼適用於單個設備跟蹤,但是當我試圖一次顯示所有設備時,它僅顯示第一個設備地址。之後,進行循環停止。我不知道我錯在哪裏。指出我的錯誤,並糾正我是否有人知道。這是我的完整的JavaScript代碼。geocoder調用在for循環中不起作用

<script type="text/javascript">  
function load() { 
      var abc; 
      var pqr; 
      function getLocation() { 
       navigator.geolocation.getCurrentPosition(showPosition); 
      } 
      function showPosition(position) { 
       abc = position.coords.latitude; 
       pqr = position.coords.longitude; 
       googlemap(abc, pqr); 
      } 
      getLocation(); 
     } 

     function googlemap(lat, lng) { 
      var x = document.getElementById("myForm"); 
      var text = ''; 
      for (var k = 0; k < x.length; k++) { 
       text += x[k].value; 
       if (k != (x.length - 1)) { 
        text += ","; 
       } 
      } 

      var names = new Array(); 
      var colors = new Array(); 
      var imeis = new Array(); 
      var times = new Array(); 
      var point; 

      var map = new google.maps.Map(document.getElementById("map"), { 
       center: new google.maps.LatLng(lat, lng), 
       zoom: 6, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      }); 

      var iconsetngs = { 
       path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW 
      }; 

      setInterval(function() { 
       downloadUrl("points.php?data=" + text, function (data) { 
        var xml = data.responseXML; 
        var points = xml.documentElement.getElementsByTagName("point"); 
        flightPlanCoordinates = new Array(); 
        var imo = ''; 
        var w = -1; 
        for (var i = 0; i < points.length; i++) { 
         if (parseFloat(points[i].getAttribute("imei")) != imo) { 
          names.push(points[i].getAttribute("name")); 
          times.push(points[i].getAttribute("time")); 
          colors.push(points[i].getAttribute("color")); 
          imeis.push(parseFloat(points[i].getAttribute("imei"))); 
          imo = parseFloat(points[i].getAttribute("imei")); 
          w++; 
          flightPlanCoordinates[w] = new Array(); 
         } 
         point = new google.maps.LatLng(
           parseFloat(points[i].getAttribute("lat")), 
           parseFloat(points[i].getAttribute("lon")) 
           ); 
         flightPlanCoordinates[w].push(point); 
        } 

        for (var j = 0; j < imeis.length; j++) { 
         var flightPath = new google.maps.Polyline({ 
          path: flightPlanCoordinates[j], 
          geodesic: true, 
          strokeColor: colors[j], 
          strokeOpacity: 1.0, 
          strokeWeight: 2, 
          icons: [{ 
            icon: iconsetngs, 
            repeat: '35px', 
            offset: '100%'}] 
         }); 

         var geocoder = new google.maps.Geocoder(); 
         geocoder.geocode({'latLng': flightPlanCoordinates[j][(flightPlanCoordinates[j].length) - 1]}, function (results, status) { 
          if (status == google.maps.GeocoderStatus.OK) { 
           if (results[1]) { 
            map.setZoom(7); 
            var marker = new google.maps.Marker({ 
             position: flightPlanCoordinates[j][(flightPlanCoordinates[j].length) - 1], 
             map: map 
            }); 
            var contentString = names[j] + times[j] + results[1].formatted_address; 
            var infowindow = new google.maps.InfoWindow({ 
             content: contentString 
            }); 
            infowindow.open(map, marker); 
           } else { 
            alert('No results found'); 
           } 
          } else { 
           alert('Geocoder failed due to: ' + status); 
          } 
         }); 

         flightPath.setMap(map); 
         geocoder.setMap(map); 

        } 
       }); 
       names = []; 
       imeis = []; 
       times = []; 
       colors = []; 
       flightPlanCoordinates = []; 
      }, 10 * 1000); 
     } 


     function downloadUrl(url, callback) { 
      var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; 
      request.onreadystatechange = function() { 
       if (request.readyState == 4) { 
        request.onreadystatechange = doNothing; 
        callback(request, request.status); 
       } 
      }; 
      request.open('GET', url, true); 
      request.send(null); 
     } 

     function doNothing() { 
     } </script> 
<body onload="load();"> 
    <form method="post" id="myForm" class="myForm" name="myForm"> 
     <select name="dvc"> 
      <option value="all">All</option> 
      <?php 
      $qry = mysql_query("SELECT * FROM devices"); 
      while ($row = mysql_fetch_array($qry)) { 
       ?> 
       <option value="<?php echo $row['device_imei']; ?>"><?php echo $row['device_name']; ?></option> 
      <?php } ?> 
     </select> 
     <input type="date" name="exct" value="<?php echo $date; ?>"/> 
     From: 
     <input type="date" name="from" /> 
     To: 
     <input type="date" name="to" /> 
    </form> 
    <button onclick="load();">Submit</button> 

    <div id="map" style="width: 100%; height: 100%"></div> 
</body> 
+0

你可以發佈一些HTML和一些樣本數據嗎?我在代碼中看不到任何實際的錯誤(儘管你的一些選擇使我感到困惑),但是如果有一些可運行的代碼(可能是一個片段或指向jsFiddle示例的鏈接),它會有所幫助。 –

+0

@http://stackoverflow.com/users/2020820/steve-k我也編輯了我的HTML代碼..而mysql數據來自XML –

+0

@Steve K我的代碼中是否有錯誤?如果沒有,那麼爲什麼它在geocoder.setMap(map);聲明。在那個語句之後,它在for循環中不會出現j = 1(imeis.length是2)。 –

回答

2

變量目前依賴於在回調執行時間,這可能不是直到實際for環飾面和j處於其最大值的j值。相反,你需要讓他們有自己的範圍。 JavaScript沒有塊作用域,所以你需要用它在另一個函數的調用是這樣的:

var createGeocodeCallback = function(n){ 
    return function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      if (results[1]) { 
       map.setZoom(7); 
       var marker = new google.maps.Marker({ 
        position: flightPlanCoordinates[n][(flightPlanCoordinates[n].length) - 1], 
        map: map 
       }); 
       var contentString = names[n] + times[n] + results[n].formatted_address; 
       var infowindow = new google.maps.InfoWindow({ 
        content: contentString 
       }); 
       infowindow.open(map, marker); 
      } else { 
       alert('No results found'); 
      } 
     } else { 
      alert('Geocoder failed due to: ' + status); 
     } 
    }; 
} 

,然後在第二循環爲您googlemap()功能,你可以這樣做:

for (var j = 0; j < imeis.length; j++) { 
    var flightPath = new google.maps.Polyline({ 
     path: flightPlanCoordinates[j], 
     geodesic: true, 
     strokeColor: colors[j], 
     strokeOpacity: 1.0, 
     strokeWeight: 2, 
     icons: [{ 
       icon: iconsetngs, 
       repeat: '35px', 
       offset: '100%'}] 
    }); 

    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({'latLng': flightPlanCoordinates[j][(flightPlanCoordinates[j].length) - 1]}, createGeocodeCallback(j)); 

    flightPath.setMap(map); 
    geocoder.setMap(map); 

} 

將數據存儲爲一個要處理的對象數組(可以訪問item.name,item.time,item.flightPlanCoordinates等),您可能會更容易,也更乾淨,因此您可以使用Array.forEach()創建回調函數,該函數負責處理整個範圍您。

+0

獲得成功。謝謝你的建議。所有問題都歸因於geocoder.setMap(map);聲明。沒有任何需要它。那聲明是錯誤的。所以,Javascript不再執行。 –

+0

如何在這段代碼中處理OVER QUERY LIMIT問題?我唯一知道的是我必須在if(status == google.maps.GeocoderStatus.OK)的其他部分做些事情。但是該怎麼辦? –

相關問題