如何判斷一個點是否在多邊形內部?算法
(1)面積和判別法:判斷目標點與多邊形的每條邊組成的三角形面積和是否等於該多邊形,相等則在多邊形內部。ide
(2)夾角和判別法:判斷目標點與全部邊的夾角和是否爲360度,爲360度則在多邊形內部。測試
(3)引射線法:從目標點出發引一條射線,看這條射線和多邊形全部邊的交點數目。若是有奇數個交點,則說明在內部,若是有偶數個交點,則說明在外部。flex
具體作法:將測試點的Y座標與多邊形的每個點進行比較,會獲得一個測試點所在的行與多邊形邊的交點的列表。在下圖的這個例子中有8條邊與測試點所在的行相交,而有6條邊沒有相交。若是測試點的兩邊點的個數都是奇數個則該測試點在多邊形內,不然在多邊形外。在這個例子中測試點的左邊有5個交點,右邊有三個交點,它們都是奇數,因此點在多邊形內。this
算法圖解:spa
關於這個算法的具體的更多圖形例子:http://alienryderflex.com/polygon/3d
參考代碼:code
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy) { int i, j, c = 0; for (i = 0, j = nvert-1; i < nvert; j = i++) { if ( ((verty[i]>testy) != (verty[j]>testy)) && (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ) c = !c; } return c; }
來自一個polygon的內部實現:blog
public bool IsInside(PointLatLng p) { int count = Points.Count; if(count < 3) { return false; } bool result = false; for(int i = 0, j = count - 1; i < count; i++) { var p1 = Points[i]; var p2 = Points[j]; if(p1.Lat < p.Lat && p2.Lat >= p.Lat || p2.Lat < p.Lat && p1.Lat >= p.Lat) { if(p1.Lng + (p.Lat - p1.Lat) / (p2.Lat - p1.Lat) * (p2.Lng - p1.Lng) < p.Lng) { result = !result; } } j = i; } return result; }
特殊狀況:要檢測的點在多變形的一條邊上,射線法判斷的結果是不肯定的,須要特殊處理(If the test point is on the border of the polygon, this algorithm will deliver unpredictable results)。ip
計算一個多邊形的面積(area of a polygon):
private static double SignedPolygonArea(List<PointLatLng> points) { // Add the first point to the end. int pointsCount = points.Count; PointLatLng[] pts = new PointLatLng[pointsCount + 1]; points.CopyTo(pts, 0); pts[pointsCount] = points[0]; for (int i = 0; i < pointsCount + 1; ++i) { pts[i].Lat = pts[i].Lat * (System.Math.PI * 6378137 / 180); pts[i].Lng = pts[i].Lng * (System.Math.PI * 6378137 / 180); } // Get the areas. double area = 0; for (int i = 0; i < pointsCount; i++) { area += (pts[i + 1].Lat - pts[i].Lat) * (pts[i + 1].Lng + pts[i].Lng) / 2; } // Return the result. return area; } /// <summary> /// Get the area of a polygon /// </summary> /// <param name="points"></param> /// <returns></returns> public static double GetPolygonArea(List<PointLatLng> points) { // Return the absolute value of the signed area. // The signed area is negative if the polygon is oriented clockwise. return Math.Abs(SignedPolygonArea(points)); }
參考資料:
http://alienryderflex.com/polygon/
http://en.wikipedia.org/wiki/Point_in_polygon
http://www.codeproject.com/Tips/84226/Is-a-Point-inside-a-Polygon