Quantcast
Channel: DotSpatial
Viewing all articles
Browse latest Browse all 3973

New Post: Split a line with another line

$
0
0
Here is a example that works given there is only one intersection:
public class TempTools
 {
       
       // Returns an an array with two linestrings from lineToSplit, if lineToSplit is intersected by traversingLine. Returns null if no interection exists. 
       public static LineString[] LineSplitter(LineString lineToSplit, LineString traversingLine)
        {
            if (!lineToSplit.Intersects(traversingLine))
                return null;

            var newLine1 = new LineString(new List<Coordinate> { });
            LineString newLine2 = null;

            var n1 = lineToSplit.Coordinates.Count;
            var n2 = traversingLine.Coordinates.Count;

            for (int i = 1; i < n1; i++)
            {
                newLine1.Coordinates.Add(lineToSplit.Coordinates[i - 1]);
                var segmL1 = new LineString(new Coordinate[] {lineToSplit.Coordinates[i-1], lineToSplit.Coordinates[i] });
                for (int j = 1; j < n2; j++)
                {
                    var segmL2 = new LineString(new Coordinate[] { traversingLine.Coordinates[j-1], traversingLine.Coordinates[j] });
                    
                    // If intersecting, identify intersection point and create new line
                    if (segmL1.Intersects(segmL2))
                    {
                        // Get intersection point
                        Coordinate intersectionPoint = segmL1.Intersection(segmL2).Coordinates[0];

                        // Insert intersection point as last point of first part of the split line and as the first point of the second part
                        if (!intersectionPoint.Equals(lineToSplit.Coordinates[i - 1]))
                            newLine1.Coordinates.Add(intersectionPoint);

                        // Create second part as new line
                        newLine2 = new LineString(new List<Coordinate> {});
                        if (!intersectionPoint.Equals(lineToSplit.Coordinates[i]))
                            newLine2.Coordinates.Add(intersectionPoint);

                        for (int k = i; k < n; k++)
                            newLine2.Coordinates.Add(lineToSplit.Coordinates[k]);

                        break;
                    }
                }

                if (newLine2 != null)
                    break;

            }

            return new LineString[] {newLine1, newLine2};
        }
    }
}
Example on how to use it:
 var splitLines = TempTools.LineSplitter(line1.BasicGeometry as LineString, line2.BasicGeometry as LineString);

Viewing all articles
Browse latest Browse all 3973

Trending Articles