Select to view content in your preferred language

Extend line (not within) up to polygon feature?

636
2
Jump to solution
06-23-2022 01:12 AM
Frequent Contributor

Hello,

I've found a script of JoshuaBixby from here:

https://community.esri.com/t5/python-questions/extend-line-up-to-polygon-feature/td-p/705806/page/2

it work well to extend lines within a polygon up to the border of the polygon feature. But it couldn't work with lines which are somehow between the polygons (see attached image - in black original line).

Could you think of a solution for this?

I tested "Have their center in" in line 21 instead of "within" but it doesn't work ...

I use notebook in ArcGIS Pro 2.9

# -*- coding: utf-8 -*-
import arcpy
import math

arcpy.env.workspace = FGDB
arcpy.env.overwriteOutput = True

dist = 100

fc_line = "line feature class"
fc_line_1 = "Sperren_C_1"
arcpy.CopyFeatures_management(fc_line, fc_line_1)
fc_line_FL = arcpy.MakeFeatureLayer_management(fc_line_1, "fc_line")

fc_poly = "Polygon Feature Class"
fc_poly_FL = arcpy.MakeFeatureLayer_management(fc_poly, "fc_poly")

with arcpy.da.SearchCursor(fc_poly_FL, "SHAPE@") as scur:
for poly, in scur:
boundary = poly.boundary()
arcpy.SelectLayerByLocation_management(fc_line_FL, "WITHIN", poly)
with arcpy.da.UpdateCursor(fc_line_FL, "SHAPE@") as ucur:
for line, in ucur:
arr, = line.getPart()
SR = line.spatialReference

p1, p2 = arr[0], arr[1]
angle = math.atan2(p2.Y - p1.Y, p2.X - p1.X)
p = arcpy.Point(p1.X - dist * math.cos(angle),
p1.Y - dist * math.sin(angle))
arr.insert(0, p)

pn1, pn = arr[len(arr)-2], arr[len(arr)-1]
angle = math.atan2(pn.Y - pn1.Y, pn.X - pn1.X)
p = arcpy.Point(pn.X + dist * math.cos(angle),
pn.Y + dist * math.sin(angle))
arr.append(p)

line = arcpy.Polyline(arr, SR, True, False)
line = line.cut(boundary)[1]

arr, = line.getPart()
p1, pn = arr[0], arr[len(arr)-1]
p1.Z, pn.Z = 0, 0
arr.insert(0, p1)
arr.append(pn)
line = arcpy.Polyline(arr, SR, True, False)

ucur.updateRow([line])

1 Solution

Accepted Solutions
by Anonymous User
Not applicable

Maybe you can store the length of the line (either original line length or after the extension) and then check it after it is cut by the boundary to see if there is a difference and go from there?

2 Replies
by Anonymous User
Not applicable

Maybe you can store the length of the line (either original line length or after the extension) and then check it after it is cut by the boundary to see if there is a difference and go from there?

Frequent Contributor

Thank you, I will try it.