开发者

Efficient way to find bounding values in an array of tuples?

I have an array of latitude/longitude values, rather like this:

var points = ["-0.开发者_如何学JAVA15868039429188,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, it's not strictly an array of tuples, but close enough.)

I want to find the four bounds of the array - i.e. the latitude and longitude north/west/south/east bounds.

Currently I'm doing this:

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

However, this doesn't feel very efficient. Can anyone recommend a better way to do it?


If you aren't constrained to the current input format you could use objects instead. This will avoid the expensive split and parseFloat calls.

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


This is very small, but there is some unnecessary overhead in using jquery's each method. You're slightly better off here using a plain for loop on the array of points.


I think your longitude tests are back-to-front:

 if (coord_lng < ebound) {
     ebound = coord_lng;

Longitude increases eastward, so the < should be >.

In a system where longitude is expressed as +ve for east and -ve for west, just east of 180° is -179° and just west is +179°. Should ebound be +179 and wbound be -179 with an interval of 358°, or the other way around with an interval of 2°?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜