2016-12-16 18 views
2

我有5000多個LatLng點,對於他們每個人我想知道他們屬於哪個特徵(區域)。這些功能來自a kmz layer by Philippe Ivaldi,轉換爲GeoJSON。分享多項功能的最佳途徑?

目前,我正在使用turkjs在雙for循環中執行此操作。如預期的那樣,計算將瀏覽器凍結十分鐘,這不是很方便。

這裏是我的代碼:

function countCeaByLayer(geoJsonLayer){ 
    jQuery.getJSON('http://localhost/server/retrieveData.php', function(data){ 
      var turfPoints = []; 
      for(var i = 0; i < data.length; i++){ 
       turfPoints.push(turf.point([data[i].longitudeWGS84, data[i].latitudeWGS84])); 
      } 

      var features = geoJsonLayer.toGeoJSON().features; 
      for(var i = 0; i < features.length; i++){ 
       var turfPointsNew = []; 
       for(var j = 0; j < turfPoints.length; j++){ 

        var isInside = turf.inside(turfPoints[j], features[i]); 
        if(!isInside) turfPointsNew.push(turfPoints[j]); 
       } 
       turfPoints = turfPointsNew; 
      } 

      console.log("done"); 
    }); 
} 

我能做些什麼來避免凍結瀏覽器?

  • 使它成爲異步?
  • 在服務器上用nodeturfjs進行計算嗎?
  • 或在nodeleaflet-headless的服務器上部署leafletjs

...或者我應該只是處理它

謝謝!

回答

1

要優化你的代碼,你應該這樣做。

循環點。

對於每個點,當您迭代多邊形以確定點是否在其中一個點內時,首先獲取多邊形邊界並查看點是否在邊界內。 如果不是,您可以跳過繼續並轉到下一個多邊形。

如果它在邊界內,請檢查它是否位於多邊形內部。

如果是這種情況,請打破循環遍歷多邊形並切換到下一個點。

例如,它可能是:

points.forEach(function(point) { 
    polygons.some(function(polygon) { 
     if (polygon.getBounds().contains(point)) { // or other method if you are not playing with Leaflet features 
      if (turf.isInside(polygon, point) { // for example, not sure this method actually exists but you get the concept 
       // point is within the polygon, do tuff 
       return true; // break the some loop 
      } 
     } 
    }); 
}); 

我有我自己的東西developped恰好做同樣的事情還根據草皮,我在客戶端上運行它(和我的循環與.some製作,而不是經典的for循環,所以它甚至可以在性能方面更進一步),而且我從未遇到凍結。

從我的角度來看,5000點是花生供瀏覽器處理,但如果你的多邊形真的很複雜(成百上千的頂點),這可能會減慢過程。

BR, 文森特

+0

*確實是花生*。我只是意識到,我的地理編碼提供商給了我'字符串'LatLngs,顯然減緩turfjs沒有警告!將它們投入「浮動」可以在幾秒鐘內完成計算。 **頭部滿貫**但是,一旦我嘗試過你的算法,我會盡快回復你,這確實會提供一個很好的速度提升。謝謝! –

+0

速度更快。做得好。 –

0

如果絞合孩子的回答是矯枉過正你,

geoJsonLayer.eachLayer(function(layer){ 
    var within = turf.within(turf.featureCollection(turfPoints),turf.featureCollection([layer.toGeoJSON()])); 
    console.dir(within); 
}); 

並確保您的座標花車,而不是字符串,因爲那是什麼原因造成的減速箱。