Search code examples
angulartypescriptmapsdrawingcesiumjs

Calculate points for a polyline inside a polygon


I'm trying to draw a polyline to display a route inside a polygon. The polylines must be parallel to each other and not go outside of the polygon.

My explanation was terrible, I want to do something like this:

map example

Any advice on where to start would be greatly appreciated!

I need to create something for CesiumJS in Angular 2 with Typescript, but any help is useful.


Solution

  • In the example you've shown, your polyline wouldn't need any actual interior points to be specified. You can create a replica of that image by specifying only the points along the rectangle's perimeter in order of the line (starting from the indicated start point). The algorithm would look something like this:

    1. Define a rectangle of interest.

    2. Define a line that describes the diagonal slope of the path within the rectangle.

    3. Generate a set of parallel lines that completely cover the rectangle, extending beyond its edges. This is done by repeatedly adding or subtracting a fixed X or Y offset to both endpoints of the original line, such that you have a set of parallel lines that extend beyond the rectangle in all directions.

    4. Iterate the set of lines in order (starting from any side and ending at the opposite side), and look for points where the line intersects the rectangle. You may need to look up an algorithm to find intersection points.

      a. For any line that does NOT intersect the rectangle exactly twice, discard the line.

      b. For the remaining lines that do intersect the rectangle exactly twice, add both of the intersection points to the polyline, but alternate the order in which they are added. In other words, if the previous line added the North intersection point and then the South intersection point, then the current line should add its South intersection point before the North intersection point, and vice versa.

    5. Now that all intersection points have been added to the polyline, you can add that polyline to your scene and render it.