[GIS] Adding vertex to line at point location using ArcPy

arcgis-10.5arcpy

I have a line layer and point layer on my ArcGIS project. The points are on the lines. I want to create vertex on lines at this point coordinates.

import arcpy

point_rows = arcpy.da.SearchCursor("D:\Test.gdb\MyPoints", ['OID@', 'SHAPE'])

rows = arcpy.UpdateCursor("D:\Test.gdb\MyLines")

for row in rows:
    geom = row.SHAPE
    for part in geom.getPart():
        for pnt in point_rows:
                row.X = pnt.X
                row.Y = pnt.Y
                rows.updateRow(row)

I could not add vertex on points, if point is on the line. How can I do this using arcpy?

Best Answer

Below is some python code that will take an un-ordered set of polylines with zero or more intersecting points and insert a vertex into the polyline at the point position.

Sample data

Sample data

This code is designed to be dropped into the Python console in ArcMap, simply change lineLayer and pointLayer.

import arcpy

# Layers in MXD
lineLayer = "fcLine"
pointLayer = "fcPoint"

with arcpy.da.UpdateCursor(lineLayer,['SHAPE@']) as lineCursor:
    for row in lineCursor:
        geom = row[0]

        # Get selected points along line, this could be zero, 1 or more
        arcpy.SelectLayerByLocation_management(pointLayer,"INTERSECT",geom,"#","NEW_SELECTION")
        res = arcpy.GetCount_management(pointLayer)
        n = int(res.getOutput(0))
        if n > 0:
            # We have at least 1 point intersecting line
            # Store selected point(s) in list for further processing
            pointList = []
            with arcpy.da.SearchCursor(pointLayer,['SHAPE@']) as pointCursor:
                for pointRow in pointCursor:
                    pointList.append(pointRow[0])
            print(str(len(pointList)) + " intersect current line.")

            # Convert polyline to points
            # Assumes line is simple geometry, i,e a single part
            lineArr = geom.getPart(0) # Returns an array
            for p in lineArr:
                pointList.append(arcpy.PointGeometry(p))

            # PointList is a list of PointGeometries composed of points on the line and points from the line itself
            # Now need to work out position of points along the line
            posDict = {}
            for p in pointList:
                pos = geom.measureOnLine(p,True)
                posDict[pos] = p

            # Reconstruct polyline by using sorted keys in posDict
            newArray = arcpy.Array()
            for key in sorted(posDict.iterkeys()):
                newArray.add(posDict[key].centroid) # Array takes points not PointGeometry, hence using centroid property
            newLine = arcpy.Polyline(newArray)

            # Insert updated geometry line back into dataset
            row[0] = newLine
            lineCursor.updateRow(row)