Skip to content

Instantly share code, notes, and snippets.

@Racum
Last active July 25, 2021 16:53
Show Gist options
  • Save Racum/eafb2e242157c3bf8d143d86e85626c2 to your computer and use it in GitHub Desktop.
Save Racum/eafb2e242157c3bf8d143d86e85626c2 to your computer and use it in GitHub Desktop.
Shapely - Resize LineString
import math
from shapely.geometry import LineString
def get_angle(line: LineString) -> float:
'Returns the angle (in radians) of a given line in relation with the X axis.'
start, end = line.boundary
if end.y - start.y == 0: # Avoids dividing by zero.
return math.acos(0)
return -math.atan((end.x - start.x) / (end.y - start.y))
def resize_line(line: LineString, length: float) -> LineString:
'Returns a new line with the same center and angle of a given line, but with different length.'
angle = get_angle(line)
ext_x = round(length / 2 * math.sin(angle), 6)
ext_y = round(length / 2 * math.cos(angle), 6)
return LineString(([line.centroid.x + ext_x, line.centroid.y - ext_y],
[line.centroid.x - ext_x, line.centroid.y + ext_y]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment