簡體   English   中英

如何從3個坐標中獲取矩形的4個坐標?

[英]How to get the 4 coordinates of a rectangle from 3 coordinates?

我想創建一個函數,允許用戶從 3 個點(藍點)繪制矩形:

  • 前兩點將形成一條邊(寬度)。
  • 第三點將決定高度。

我需要在傳單中使用這個自定義繪制函數,但是傳單的默認矩形是用 2 個對角點創建的: https : //leafletjs.com/reference-1.5.0.html#rectangle

我需要計算一個綠點,但我的小腦袋似乎無法弄清楚:P

PS/EDIT:矩形可能是有角度的,這就是它具有挑戰性的原因

在此處輸入圖片說明

Leaflet 的默認矩形是用 2 個對角點創建的

[...]

矩形可能是有角度的,這就是它具有挑戰性的原因

要知道,單頁的L.Rectangle從創建L.LatLngBounds ,邊框其中邊緣被隱式對准坐標網格 不要使用邊界框,而是依靠L.Polygon ,提供所有四個點。


設 A 和 B 是矩形底部的點,C 是頂部的點。 假設所有點都是{x: Number, y: Number}形式的 Javascript 結構,並假設您在歐幾里得平面上工作(即不在大地水准面的表面上),

首先, 計算一點到另外兩點定義的直線的距離,即C到AB定義的直線的距離。 讓它成為distance (請注意,它等於圖中的“高度”):

var distance = Math.abs( 
    (A.y - B.y) * C.x  -  (A.x - B-x) * C.y  +  B.x * A.y  -  B.y * A.x ) 
  ) / Math.sqrt(
    Math.pow(B.y - A.y, 2) + Math.pow(B.x - A.x, 2)
  );

然后,設AB為從A到B的向量

var AB = {  x: B.x - A.x,   y: B.y - A.y };

(注意AB的長度等於你圖中的“寬度”)

計算垂直於 AB 的單位向量

var perpendicular = {x: -AB.y, y: AB.x}
var perpendicularSize = Math.sqrt(AB.x * AB.x + AB.y * AB.y);
var unit = {x: perpendicular.x / perpendicularSize, y: perpendicular.y / perpendicularSize};

將該單位向量乘以從 C 到 AB 的距離,以獲得矩形“邊”的向量:

var sideVector = { x: unit.x * distance, y: unit.y * distance };

...並通過將 A 和 B 偏移矩形邊的向量來創建新點 D 和 E:

var D = { x: A.x + sideVector.x, y: A.y + sideVector.y };
var E = { x: B.x + sideVector.x, y: B.y + sideVector.y };

...您的矩形現在由點 ABDE 定義。 請注意,C 在由點 DE 定義的直線上。

假設提供了這 3 個點的坐標, - 2, 5(第一點) - 5, 5(第二點) - x, 8(第三點)

第一個綠色將從前兩個點之一取 x 假設從第一個點 => 2 和 y 從第三個點 => 8 所以第一個綠色點在 2,8

第二個將從第二個點取 x => 5,從第三個點取 y => 8 所以第二個綠點在 5,8

我不確定我是否正確理解了答案。

假設 edge1 = [x1,y1] , edge2 = [x2,y2]

def calculate_edges (edge1,edge2,height)
    edge3 [0] = edge1[0]          //x3
    edge3 [1] = edge1[1] + height //y3
    edge4 [0] = edge2[0]          //x4
    edge4 [1] = edge2[1] + height //y4
return edge3,edge4

對於 Python:

#Given three points fit a rectangle

import math 
a,b,c=[1,4],[3,4],[3,10] #Sample numbers

#Distance from dot C to line AB (https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points)
distance= abs((b[1]-a[1])*c[0] - (b[0]-a[0])*c[1] + b[0]*a[1] - b[1]*a[0] ) / math.sqrt((b[1]-a[1])**2 + (b[0]-a[0])**2)
print(distance)
#let AB be the vector from A to B
ab=[b[0]-a[0],b[1]-a[1]]

#unit vector perpendicular to AB (https://en.wikipedia.org/wiki/Unit_vector)
perpendicularSize = math.sqrt(ab[0]**2+ab[1]**2)
unit = [-ab[1]/perpendicularSize ,ab[0]/perpendicularSize]

#Multiply that unit vector by the distance from C to AB to get the vectors for the "sides" of your rectangle
sideVector = [unit[0]*distance,unit[1]*distance]

#create new points D and E by offsetting A and B by the vector for the sides of the rectangle
d=[a[0]+sideVector[0],a[1]+sideVector[1]]
e=[b[0]+sideVector[0],b[1]+sideVector[1]]

print(e,d)  #[3.0, 10.0] [1.0, 10.0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM