在元组数组中查找边界值的有效方法?

时间:2011-06-01 14:24:31

标签: javascript jquery

我有一个纬度/经度值数组,就像这样:

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"];

(好吧,它不是严格意义上的元组数组,但足够接近。)

我想找到数组的四个边界 - 即纬度和经度北/西/南/东边界。

目前我正在这样做:

                $.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;
                  }
              });

但是,这感觉效率不高。任何人都可以推荐更好的方法吗?

3 个答案:

答案 0 :(得分:2)

如果您不受当前输入格式的限制,则可以使用对象。这样可以避免昂贵的splitparseFloat来电。

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

答案 1 :(得分:0)

这个非常小,但使用jquery的each方法有一些不必要的开销。使用点数组上的普通for循环,你会稍微好一点。

答案 2 :(得分:0)

我认为您的经度测试是反向的:

 if (coord_lng < ebound) {
     ebound = coord_lng;

经度向东增加,因此<应为>

在经度表示东经+ ve和西经-ve的系统中,180°以东为-179°,西正为+ 179°。 ebound是+179,wbound是-179,间隔是358°,还是相反,间隔为2°?