Find direction from rectangle points

Viewed 100

I am trying to figure out the direction of corner from four coordinates. Maybe an example can describe better than my words..

    var points = [
     [0, 0], // top-left
     [50, 0], // top-right
     [50, 50], // bottom-right
     [0, 50], // bottom-left
   ]; // order can be random

    var topLeft =[9999, 9999]; 
    var topRight =[0, 9999]; 
    var bottomRight =[0, 0]; 
    var bottomLeft =[9999, 0]; 

    points.forEach((p) {
      if (p[0] < topLeft[0] && p[1] < topLeft[1]) topLeft = p;
      if (p[0] > topRight[0] && p[1] < topRight[1]) topRight = p;
      if (p[0] > bottomRight[0] && p[1] > bottomRight[1]) bottomRight = p;
      if (p[0] < bottomLeft[0] && p[1] > bottomLeft[1]) bottomLeft = p;
    });

    print([tl, tr, br, bl]);

  // [[0, 0], [50, 0], [50, 50], [50, 50]] - wrong
  // [[0, 0], [50, 0], [50, 50], [0, 50]] - right 

I have a list of 4 coordinate points. Trying to separate them according to their direction, like top-left, top-right, bottom-left, bottom-right etc.. but my code is not working correctly (top-right & bottom-left are wrong), could you please help me to solve this issue, as well as how can I make it more efficient?

1 Answers

You missed the = (equal sign) in if conditions. Here is the updated code.

void main() {
  var points = [
     [0, 0], // top-left
     [50, 0], // top-right
     [50, 50], // bottom-right
     [0, 50], // bottom-left
   ]; // order can be random

    var topLeft =[9999, 9999]; 
    var topRight =[0, 9999]; 
    var bottomRight =[0, 0]; 
    var bottomLeft =[9999, 0]; 

    points.forEach((p) {
      if (p[0] <= topLeft[0] && p[1] <= topLeft[1]) topLeft = p;
      if (p[0] >= topRight[0] && p[1] <= topRight[1]) topRight = p;
      if (p[0] >= bottomRight[0] && p[1] >= bottomRight[1]) bottomRight = p;
      if (p[0] <= bottomLeft[0] && p[1] >= bottomLeft[1]) bottomLeft = p;
    });

    print([topLeft, topRight, bottomRight, bottomLeft]);
}
Related