2011-06-01 68 views
1

我有緯度/經度值的陣列,而不是像這樣:查找元組數組中的邊界值的有效方法?

var points = ["-0.15868039429188,51.534183502197", "-0.158839,51.534916", "-0.158814,51.53503", "-0.158817,51.535076", "-0.157492,51.535404", "-0.155767,51.535816", "-0.155696,51.535831", "-0.15526,51.535934", "-0.153192,51.536388", "-0.152282,51.536575", "-0.152467,51.536968", "-0.152592,51.53727", "-0.152682,51.53756", "-0.152074,51.53754", "-0.151921,51.537464", "-0.151732,51.538368", "-0.151373,51.538841", "-0.150622,51.539482", "-0.150237,51.539761", "-0.150047,51.539875", "-0.149957,51.539921", "-0.149594,51.540108", "-0.149563,51.540134", "-0.149536,51.540161", "-0.149497,51.540184", "-0.149445,51.540203"]; 

(OK,這不是嚴格的元組的數組,但足夠接近。)

我想找到這四個界限的陣列 - 即經度和緯度的北/西/南/東界。

目前我在做這個:

   $.each(coords, function(index, value) { 
        var j = value.split(','); 
        var coord_lat = parseFloat(j[1]); 
        var coord_lng = parseFloat(j[0]); 
        if (coord_lat>nbound) { 
         nbound = coord_lat; 
        } else if (coord_lat<sbound) { 
         sbound = coord_lat; 
        } 
        if (coord_lng<ebound) { 
         ebound = coord_lng; 
        } else if (coord_lng>wbound) { 
         wbound = coord_lng; 
        } 
       }); 

然而,這並不覺得很有效。任何人都可以推薦更好的方法來做到這一點?

+1

你的代碼沒問題。你只觸摸每個元素一次。你如何設置nbound sbound等的默認值? – jantimon 2011-06-01 14:29:34

+0

謝謝。我只是使用數組中的第一項。 – Richard 2011-06-01 14:30:36

+2

你也可以看看http://codereview.stackexchange.com/。 – pimvdb 2011-06-01 14:31:36

回答

2

如果您不受限於當前輸入格式,則可以使用對象。這將避免昂貴的splitparseFloat調用。

var points = [ 
    { latitude: -0.15868039429188, longitude: 51.534183502197 }, 
    { latitude: -0.158839, longitude: 51.534916 }, 
    { latitude: -0.155696, longitude: 51.535831 } 
]; 
0

這是非常小的,但使用jquery的each方法有一些不必要的開銷。在這裏使用點陣列上的普通for循環略勝一籌。

+0

這主要在** IE6,IE7 **中引人注意,但取決於點數,它肯定會加起來。 – ChaosPandion 2011-06-01 14:36:43

0

我覺得你的經度測試後到前:向東

if (coord_lng < ebound) { 
    ebound = coord_lng; 

經度的增加,所以<應該>

在一個系統中,經度表示爲+ ve爲東,-ve爲西,180°的東邊是-179°,西邊是+ 179°。 ebound應爲+179,wbound爲-179,間隔爲358°,或者相反,間隔爲2°?

相關問題