/// <summary> /// 检查点是否在Polygon中 /// </summary> /// <param name="p">点</param> /// <param name="polygon">多边型</param> /// <returns>在则返回true,否则返回false</returns> public static bool PointInPolygon(Point p, Polygon polygon) { bool result = CheckPointOnPolygonLine(p, polygon); if (result) return true; result = PointInTheMaxRectangle(p, polygon); if (!result) return false; result = LineSegmentIntersectionInPolygonLine(p, polygon); return result; }
private bool InArea(decimal lat, decimal lon, out LocationInfo locationInfo) { locationInfo = null; foreach (var item in ltPToL) { Polygon polygon = new Polygon(item.Points); double x = Convert.ToDouble(lat); double y = Convert.ToDouble(lon); Point point = new Point(x, y); bool isIn = Polygon.PointInPolygon(point, polygon); if (isIn) { locationInfo = item.LocationInfo; return true; } } return false; }
private static bool LineSegmentIntersectionInPolygonLine(Point p, Polygon polygon) { int intersectionCount = 0; double maxX = GetMaxPointX(polygon.Points); if (p.X > maxX) { maxX = p.X + 1; } else { maxX += 1; } LineSegment mainLine = new LineSegment(p, new Point(maxX, p.Y)); for (int i = 0, j = 1; j < polygon.Points.Count; i++, j++) { LineSegment line = new LineSegment(polygon.Points[i], polygon.Points[j]); bool result = LineSegment.LineSegmentIntersection(mainLine, line); if (result) intersectionCount++; } LineSegment lastLine = new LineSegment(polygon.Points[polygon.Points.Count - 1], polygon.Points[0]); bool lastResult = LineSegment.LineSegmentIntersection(mainLine, lastLine); if (lastResult) intersectionCount++; if ((intersectionCount % 2) == 0) return false; return true; }
public static bool PointInTheMaxRectangle(Point p, Polygon polygon) { double maxX = polygon.Points.Max(u => u.X); double minX = polygon.Points.Min(u => u.X); double maxY = polygon.Points.Max(u => u.Y); double minY = polygon.Points.Min(u => u.Y); LineSegment line = new LineSegment(new Point(maxX, maxY), new Point(minX, minY)); Rectangle rec = new Rectangle(line); return Rectangle.PointInRectangle(p, rec); }
private static bool CheckPointOnPolygonLine(Point p, Polygon polygon) { for (int i = 0, j = 1; j < polygon.Points.Count; i++, j++) { LineSegment line = new LineSegment(polygon.Points[i], polygon.Points[j]); if (LineSegment.PointOnTheLine(p, line)) return true; } LineSegment lastLine = new LineSegment(polygon.Points[polygon.Points.Count - 1], polygon.Points[0]); if (LineSegment.PointOnTheLine(p, lastLine)) return true; return false; }