1

I want to copy and merge selected features (lines) at a time in destination layer (line).

Is there anyway to do this in ArcGIS 10.2 for Desktop?

Update: My current method involves two clicks using copy and merge. I used to copied selected linear features and paste to destination layer(selection remains same) and merge it via Editor toolbox.

  • Try the append tool. – Emil Brundage Dec 20 '14 at 5:01
  • Its not like processing large data set. It is just copying and then merge tool in editor. we used to do twice for this ..I need to do in one go.. – GIS Data Butcher Dec 20 '14 at 5:05
  • Would you be able to edit your question to describe your precise current steps to do this, please? Perhaps this can lead to how you could do it using less steps. – PolyGeo Dec 20 '14 at 5:16
  • I used to copy selected linear feature and copied to destination layer(selection remains same) and merge it via Editor Toolbox. – GIS Data Butcher Dec 20 '14 at 5:25
6

Your steps are the minimum if you are appending to an existing feature class in an Edit session using manual Editor tools. In fact, you are not doing 2 manual steps, you are doing 4 manual steps after selecting the lines you want to use. Step 1 copy lines, Step 2 paste lines, Step 3 initiate Merge, Step 4 choose one line from the selected set of lines that will apply attributes to the merged geometry (including confirmation of the selected line with the OK button, but I won't count that as a 5th step). The first three steps can be automated to a single button click only by creating a custom python script tool, but the fourth step still needs another user click to choose the attributes, unless you have an easy to program rule that governs that selection.

[EDIT: Replaced script description with actual Python Toolbox script:]

Create a Python Toolbox. Edit the toolbox (right click the toolbox and choose Edit) and replace the default script with the following script. Change the layer names for the inLyr and outLyr to match the input line selection layer name and merged line layer name in your open map (locate and edit the lines after """****CUSTOMIZE THE INPUT AND OUTPUT LAYER NAMES****""" in the script). Select features and use the "Paste Merge Tool" in the toolbox. You should be able to place this tool on a button on a toolbar to run it.

The tool checks to make sure a feature is selected in the input layer. It also works for both Polylines and Polygons. I made the default attribute rule that the original selected longest line segment or largest polygon area would provide the attributes of the dissolved line for all editable matching fields to avoid requiring user input. The Attribute Transfer tool could manually override those attributes after the feature is created if that rule is not the one the user wanted to follow. I added the arcpy.RefreshActiveView() method after inserting the new feature and this made the feature appear on the map. However, if an Editor session is active the feature is not saved automatically and when the edit session is stopped a warning will not appear and the screen will not refresh to show that the feature did not save and is no longer really supposed to be visible. I still have to look into that later.

import arcpy
"""Set the workspace to in_memory for temporary feature classes."""
from arcpy import env
env.workspace = "in_memory"


class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "Toolbox"
        self.alias = ""

        # List of tool classes associated with this toolbox
        self.tools = [PasteMergeTool]


class PasteMergeTool(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Paste Merge Tool"
        self.description = ""
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""
        params = None
        return params

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def execute(self, parameters, messages):
        """The source code of the tool."""
        try:
            """****CUSTOMIZE THE INPUT AND OUTPUT LAYER NAMES****"""
            inLyrName = "ParcelAssessor"
            outLyrName = "CONDOMINIUMS_ASSESSOR"

            """Get the current map layers."""
            mxd = arcpy.mapping.MapDocument("CURRENT")

            """****CUSTOMIZE THE INPUT LAYER****"""
            inLyr = arcpy.mapping.ListLayers(mxd, inLyrName)[0]

            """Check for at least 1 selected feature."""
            desc=arcpy.Describe(inLyr)
            if len(desc.FIDSet) == 0:
                arcpy.AddMessage("No features selected!  Please select at least 1 feature.")
                return

            inShapeType = desc.shapeType
            if not inShapeType in ["Polyline", "Polygon"]:
                arcpy.AddMessage("Input features must be Polyline or Polygon!")
                return

            """****CUSTOMIZE THE OUTPUT LAYER****"""
            outLyr = arcpy.mapping.ListLayers(mxd, outLyrName)[0]

            desc=arcpy.Describe(outLyr)

            outShapeType = desc.shapeType
            if inShapeType != outShapeType:
                arcpy.AddMessage("Input features must both be %s" % inShapeType)
                return

            """Get all Output Fields and Matched Input/Output Fields lists."""
            inFields = arcpy.ListFields(inLyr)
            outFields = arcpy.ListFields(outLyr)

            if inShapeType == "Polyline":
                matchedFields = ["Shape@Length"]
            else:
                matchedFields = ["Shape@Area"]
            for outField in outFields:
                for inField in inFields:
                    if outField.name == inField.name and not outField.name.upper() in ['SHAPE_LENGTH', 'SHAPE_AREA'] and outField.type == inField.type and not outField.type in ["OID", "GlobalID", "GUID", "Geometry"]:
                        matchedFields.append(outField.name)

            print matchedFields
            arcpy.AddMessage(matchedFields)

            """make sure overwriteOutput is True"""
            overwrite = env.overwriteOutput
            env.overwriteOutput = True

            """Dissolve output layer's selected features without attributes to an in_memory fc."""
            dissolve = arcpy.Dissolve_management(inLyr, "temp_Dissolve")
            cursor = arcpy.da.SearchCursor(dissolve, ["Shape@"])
            geom = None
            for row in cursor:
                geom = row[0]
            del cursor
            arcpy.AddMessage('The dissolved segment measures %12.3f' % geom.length)

            """Reset overwriteOutput to user's original setting"""
            env.overwriteOutput = overwrite

            """Get the longest polyline segment length."""
            length = 0
            valueList = []      
            cursor = arcpy.da.SearchCursor(inLyr, matchedFields)
            for row in cursor:
                if row[0] > length:
                    length = row[0]
                    valueList = []
                    for n in range (1,len(matchedFields)):
                        valueList.append(row[n])
            del cursor
            if inShapeType == "Polyline":
                arcpy.AddMessage('The longest selected segment measures %12.3f' % length)
            else:
                arcpy.AddMessage('The largest selected polygon has an area of %12.3f' % length)


            print valueList
            arcpy.AddMessage(valueList)


            """Remove Shape@Length field from matchedFields list and add Shape@."""
            matchedFields.pop(0)
            matchedFields.append("Shape@")

            """Add Geometry to attribute valueList."""
            valueList.append(geom)

            """Create row object for insertion."""
            insRow = tuple(valueList)

            """Insert new feature into output layer."""
            cursor = arcpy.da.InsertCursor(outLyr, matchedFields)
            cursor.insertRow(insRow)
            del cursor

            arcpy.RefreshActiveView()

        except Exception as e:
            print e.message
            arcpy.AddError(e.message)

        return
| improve this answer | |
  • Can I have some piece of code just for guidance. – GIS Data Butcher Dec 20 '14 at 6:36
  • I have replaced my description of a possible script with an actual Python toolbox script. Try it. – Richard Fairhurst Dec 20 '14 at 19:57
  • I fixed a code error after my last comment, so if you get a tool that won't compile or that throws an error replace the toolbox script with the most recently revised code in my post. – Richard Fairhurst Dec 20 '14 at 20:16
  • 1
    I have modified the code further to make sure at least 1 input feature is selected before dissolving the features, so that the entire set of input features is not dissolved. I also made the code work for either Polylines or Polygons, as long as both the input and output layers' shape types match. For Polylines the longest selected input polyline provides the attributes and for Polygons the selected input polygon with the largest area provides the attributes for the new dissolved feature. – Richard Fairhurst Dec 20 '14 at 21:20
  • That piece code works nice however second time when I execute it gives Error. ERROR 000725: Output Feature Class: Dataset C:\Users\sanjay\Documents\ArcGIS\Default.gdb\temp_Dissolve already exists I checked out that location it creates layer named temp_Dissolve. So how to go without it. And One more how to make it work on button. I am clueless how to create button in arcmap that contains this code when i click it should work without popping out extra dialogue box. – GIS Data Butcher Dec 21 '14 at 10:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.