from shapely.geometry import LineString
from shapely.ops import transform
import math
def offset_curve(line: LineString, distance: float) -> LineString:
"""
Create an offset curve to the left or right of a LineString.
:param line: The input LineString object.
:param distance: Positive distance creates the right offset, negative for left offset.
:return: A new LineString representing the offset curve.
"""
# Define a function to perform the offset using Shapely
def offset_point(x, y):
# Calculate the angle (theta) of the line
angle = math.atan2(y, x) + (math.pi / 2) # Rotate 90 degrees
# Calculate the new x and y offsets
return x + distance * math.cos(angle), y + distance * math.sin(angle)
# Transform the LineString to apply the offset
return transform(offset_point, line)
# Example usage:
if __name__ == "__main__":
# Create a LineString
original_line = LineString([(0, 0), (1, 1), (2, 0), (3, 1)])
# Create an offset curve
right_offset = offset_curve(original_line, 0.1) # Offset to the right
left_offset = offset_curve(original_line, -0.1) # Offset to the left
# Print the results
print("Original Line:", original_line)
print("Right Offset Line:", right_offset)
print("Left Offset Line:", left_offset)
Keep in mind that this function is a basic implementation and may not handle all edge cases, such as self-intersecting lines or complex geometries. If you need robust handling of geometries, ensure to test the function extensively for your use cases.