WebGIS中一些功能算法實例
1、如何判斷平面內兩條線是否相交并返回交點?
/// <summary>
/// 判斷平面內兩條線是否相交并返回交點
/// </summary>
/// <param name="a">線段1起點坐標</param>
/// <param name="b">線段1終點坐標</param>
/// <param name="c">線段2起點坐標</param>
/// <param name="d">線段2終點坐標</param>
/// <param name="intersection">相交點坐標</param>
/// <returns>是否相交 0:兩線平行 -1:不平行且未相交 1:兩線相交</returns>
public static int GetIntersection(ESRI.ArcGIS.Client.Geometry.MapPoint a, ESRI.ArcGIS.Client.Geometry.MapPoint b, ESRI.ArcGIS.Client.Geometry.MapPoint c, ESRI.ArcGIS.Client.Geometry.MapPoint d, ref ESRI.ArcGIS.Client.Geometry.MapPoint intersection)
{
a = new MapPoint(Math.Round(a.X, 3), Math.Round(a.Y, 3));
b = new MapPoint(Math.Round(b.X, 3), Math.Round(b.Y, 3));
c = new MapPoint(Math.Round(c.X, 3), Math.Round(c.Y, 3));
d = new MapPoint(Math.Round(d.X, 3), Math.Round(d.Y, 3));
//判斷異常
if (Math.Abs(b.X - a.Y) + Math.Abs(b.X - a.X) + Math.Abs(d.Y - c.Y) + Math.Abs(d.X - c.X) == 0)
{
/*
if (c.X - a.X == 0)
Debug.Print("ABCD是同一個點!");
else
Debug.Print("AB是一個點,CD是一個點,且AC不同!");
*/
return 0;
}
if (Math.Abs(b.Y - a.Y) + Math.Abs(b.X - a.X) == 0)
{
/*
if ((a.X - d.X) * (c.Y - d.Y) - (a.Y - d.Y) * (c.X - d.X) == 0)
Debug.Print("A、B是一個點,且在CD線段上!");
else
Debug.Print("A、B是一個點,且不在CD線段上!");
*/
return 0;
}
if (Math.Abs(d.Y - c.Y) + Math.Abs(d.X - c.X) == 0)
{
/*
if ((d.X - b.X) * (a.Y - b.Y) - (d.Y - b.Y) * (a.X - b.X) == 0)
Debug.Print("C、D是一個點,且在AB線段上!");
else
Debug.Print("C、D是一個點,且不在AB線段上!");
*/
return 0;
}
if ((b.Y - a.Y) * (c.X - d.X) - (b.X - a.X) * (c.Y - d.Y) == 0)
{
//Debug.Print("線段平行,無交點!");
return 0;
}
intersection.X = ((b.X - a.X) * (c.X - d.X) * (c.Y - a.Y) - c.X * (b.X - a.X) * (c.Y - d.Y) + a.X * (b.Y - a.Y) * (c.X - d.X)) / ((b.Y - a.Y) * (c.X - d.X) - (b.X - a.X) * (c.Y - d.Y));
intersection.Y = ((b.Y - a.Y) * (c.Y - d.Y) * (c.X - a.X) - c.Y * (b.Y - a.Y) * (c.X - d.X) + a.Y * (b.X - a.X) * (c.Y - d.Y)) / ((b.X - a.X) * (c.Y - d.Y) - (b.Y - a.Y) * (c.X - d.X));
if ((intersection.X - a.X) * (intersection.X - b.X) <= 0 && (intersection.X - c.X) * (intersection.X - d.X) <= 0 && (intersection.Y - a.Y) * (intersection.Y - b.Y) <= 0 && (intersection.Y - c.Y) * (intersection.Y - d.Y) <= 0)
{
// Debug.Print("線段相交于點(" + intersection.X + "," + intersection.Y + ")!");
return 1; //'相交
}
else
{
//Debug.Print("線段相交于虛交點(" + intersection.X + "," + intersection.Y + ")!");
return -1; //'相交但不在線段上
}
}
本文由用戶 nnf6 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!