How determine if point is within rectangle given all latitude/longitude coordinates?

前端 未结 1 1761
醉梦人生
醉梦人生 2021-01-07 05:06

If given x/y coordinates for all 4 corners of rectangle, and then another x/y, it\'s easy to determine if the point is within the rectangle if top left is 0,0.

But w

相关标签:
1条回答
  • 2021-01-07 05:23

    Mathematicaly, you could use inequations to determine that.

    edit: When doing the example, i've noticed you put the coordinates in the inverse format (y,x) instead of (x,y). In my example I use (x,y) format, so I just inverted the order to easy my explanation.

    Let's say A = (-130,10) B = (-100,20) C = (-125,-5) D = (-100,5)

    You build an inequation from your rectangle edges :

    if( (x,y) < AB && (x,y) > AC && (x,y) > CD && (x,y) < BD) then
        (x,y) belongs to rectangle ABCD
    end if
    

    If all inequations are true, then your point belongs to the rectangle


    Concrete example :

    AB represent the segment but can be represented by a formula : y = ax + b

    to determine a (the slope of the formula, not the point A) you get the difference of

    (Ay - By) / (Ax - Bx) 
    

    Ay means Y component of point A wich is 10 in that case

    That formula gives us

    (10 - 20) / (-130 - -100) = -10 / -30 = 1/3
    

    Now we have

    y = x/3 + b
    

    We now determine b. We now that both point A and B belongs to that formula. So we take any of them to replace the x,y values in the formula. Let's take point B :

    20 = -100/3 + b
    

    We isolate b giving us :

    b = -100 / 60 = -10/6
    

    We have now

    y = x/3 - (6/10)
    

    So if we want to determine if Point Z (10, 15) belongs to your retangle, you check firstly if

    y > x/3 - (10/6)
    

    Then in the case of Z(10, 15) :

    15 > 10/3 - (10/6)
    
    15 > 10/6
    
    15 > 1.66 is true
    

    So condition is met for this edge. You need to this same logic for each edges.

    Note that to determine if you use > or <, you need to tell if at a certain x value, our point has a bigger y or smaller y value than our rectangle edge.

    You can use < and > if you want a point to be strictly inside the rectangle; <= and >= if a point on the rectangle's edge belongs to the rectangle too. You decide.

    I hope that my explanation is clear. Feel free to ask more if some points are unclear.

    0 讨论(0)
提交回复
热议问题