def validateandrun(thingtodo, answer, clickedx, clickedy): # set active mxd, and layer which is currently selected in the TOC mxd = arcpy.mapping.MapDocument("CURRENT") lyr = arcpy.mapping.ListLayers( mxd, pythonaddins.GetSelectedTOCLayerOrDataFrame())[0] try: matchcount = len(lyr.getSelectionSet()) except: # error message if a layer and a row within that layer are not both selected pythonaddins.MessageBox("select both layer and row", "Error", {0}) else: # check that only one row is selected if matchcount == 1: # calls a function to to one of: update attribute (1), move the point (2), move view to next point (3), # reset to original point location (4), or visualize the current and original location of points (5) if thingtodo == 1: # filling text into grod_eva field groddecide(answer) elif thingtodo == 2: # there will be a move with two extra parameters movepoint(clickedx, clickedy) elif thingtodo == 3: # button next point pantonext() elif thingtodo == 4: # the moved point will be reset to its original location resetpoint() elif thingtodo == 5: # filling text into curb field curbdecide(answer) elif thingtodo == 6: # filling text into evaluation field evaluate(answer) else: # error message if multiple rows are selected pythonaddins.MessageBox("more than one row selected", "Error", {0})
def onClick(self): try: workspace = autoPath() mxd = arcpy.mapping.MapDocument("CURRENT") ddp = mxd.dataDrivenPages dfLst = arcpy.mapping.ListDataFrames(mxd) pageName = ddp.pageRow.getValue(ddp.pageNameField.name) # Set data frame name to credits field (can change to description field) for use in lyrString. for df in dfLst: for lyr in arcpy.mapping.ListLayers(mxd, "*", df): if isinstance( lyr, arcpy.mapping.Layer) and not lyr.isGroupLayer: lyr.credits = df.name lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame() if not isinstance(lyr, arcpy.mapping.Layer) or lyr.isGroupLayer: pythonaddins.MessageBox( 'Please select one (1) layer (not a group or data frame or multiple layers) in the Table Of Contents', 'Layer Selection Error', 0) else: lyrString = "%s_%s_%s.lyr" % (pageName, lyr.name, lyr.credits) arcpy.SaveToLayerFile_management(lyr, workspace + "\\" + lyrString, "ABSOLUTE") pythonaddins.MessageBox( "%s layer saved to:\n\n%s\n\nas:\n\n%s" % (lyr.name, workspace, lyrString), "Layer Saved", 0) except Exception as e: pythonaddins.MessageBox(e, "Error")
def clearSelectedLayerQuery(): """Clear definition query from the layer selected in the T.O.C.""" import pythonaddins lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame() lyr.definitionQuery = "" print "Definition query for '{}'' layer cleared.".format(lyr.name) arcpy.RefreshActiveView()
def onClick(self): global raster2 lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame() if isinstance(lyr, arcpy.mapping.Layer) and lyr.isRasterLayer: raster2 = lyr else: pythonaddins.MessageBox('Please select a raster layer.', 'Error')
def onClick(self): env.overwriteOutput = True lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame() if isinstance(lyr, arcpy.mapping.Layer) and lyr.isRasterLayer: noDataBackground = Con(Raster(lyr.name) != 0, lyr.name) fileParts = os.path.splitext(lyr.name) savePath = '{0}/{1}-noBG{2}'.format(lyr.workspacePath, fileParts[0], fileParts[1]) noDataBackground.save(savePath) result = arcpy.MakeRasterLayer_management( savePath, '{0}-noBG'.format(fileParts[0])) elif isinstance(lyr, list): for i in range(len(lyr)): if lyr[i].isRasterLayer: noDataBackground = Con( Raster(lyr[i].name) != 0, lyr[i].name) fileParts = os.path.splitext(lyr[i].name) savePath = '{0}/{1}-noBG{2}'.format( lyr[i].workspacePath, fileParts[0], fileParts[1]) noDataBackground.save(savePath) result = arcpy.MakeRasterLayer_management( savePath, '{0}-noBG'.format(fileParts[0])) else: pythonaddins.MessageBox('Please select a raster layer.', 'Error') else: pythonaddins.MessageBox('Please select a raster layer.', 'Error')
def selectedLayer(): """ Return the selected layer object, verify that it's point data.""" layer = None if config.selected_layer: # our preference is to always use the selected_layer object, which is # populated by our combination box. layer = config.selected_layer else: # if no layer is set, default to the current layer in the TOC layer = pythonaddins.GetSelectedTOCLayerOrDataFrame() desc = arcpy.Describe(layer) if layer is None or desc.datasetType not in config.allowed_formats: msg = "No layer selected! Please select a point layer from the table of contents." title = "No selected layer" pythonaddins.MessageBox(msg, title) else: if desc.shapeType not in config.allowed_types: msg = "Selected layer doesn't contain points." title = "No points in layer" pythonaddins.MessageBox(msg, title) layer = None # set our default SRID based on the input data layer config.sr = desc.spatialReference return layer
def Effects(object): mxd = arcpy.mapping.MapDocument('current') df = pythonaddins.GetSelectedTOCLayerOrDataFrame() if (df.isFeatureLayer == True) or (df.isGroupLayer == True) or ( df.isRasterLayer == True) or (df.isServiceLayer == True): df.visible == True else: df.visible == False
def onStopOperation(self): print("%d onStopOperation(self)" % self.count) self.count += 1 #self.say_what() desc = self.currentFeature selections = self.editSelection workspace = self.editWorkspace print("Workspace ", workspace) print("Selected ", selections) print("currentLayer", self.currentLayer) obj = pythonaddins.GetSelectedTOCLayerOrDataFrame() print("current thing", obj)
def clearSelectedLayerQuery(): """Clear definition query from the layer selected in the T.O.C.""" try: import arcpy, pythonaddins lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame() lyr.definitionQuery = "" print "Definition query for '{}'' layer cleared.".format(lyr.name) arcpy.RefreshActiveView() except AttributeError as e: pythonaddins.MessageBox( "Please select a layer in the T.O.C to clear it's query", "Error") print e
def onClick(self): layer_files = pythonaddins.OpenDialog('Select Layers to Add', True, r'C:\ArcpyBook\data\Wildfires', 'Add') mxd = arcpy.mapping.MapDocument('current') df = pythonaddins.GetSelectedTOCLayerOrDataFrame() if not isinstance(df, arcpy.mapping.Layer): for layer_file in layer_files: layer = arcpy.mapping.Layer(layer_file) arcpy.mapping.AddLayer(df, layer) else: pythonaddins.MessageBox('Select a data frame', 'INFO', 0)
def onFocus(self, focused): self.mxd = arcpy.mapping.MapDocument('current') layer = pythonaddins.GetSelectedTOCLayerOrDataFrame() if focused: if isinstance(layer, arcpy.mapping.Layer): fields = arcpy.ListFields(layer) self.items = [] for f in fields: self.items.append(f.name) print self.items else: pythonaddins.MessageBox("please select a layer!", 'INFO', 0) exit
def onRectangle(self, rectangle_geometry): # Get selected layer. lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame() # Make sure it's a raster layer. if isinstance(lyr, arcpy.mapping.Layer) and lyr.isRasterLayer: # Get raster object. raster = arcpy.Raster(lyr.dataSource) # Clip the raster. clipped = arcpy.Clip_management(lyr, str(rectangle_geometry), 'clipped-{0}.tif'.format(lyr.name)) else: # Show a message if a raster layer wasn't selected. pythonaddins.MessageBox('Please select a raster layer.', 'Error')
def evaluate(answer): mxd = arcpy.mapping.MapDocument("CURRENT") lyr = arcpy.mapping.ListLayers( mxd, pythonaddins.GetSelectedTOCLayerOrDataFrame())[0] # create cursor for selected point with arcpy.da.UpdateCursor(lyr, ["count", evaluatefield]) as features: for feature in features: # update decision field with user's answer feature[1] = str(answer) # update attributes to store values of current x and y coordinates of the point WITHOUT moving it features.updateRow(feature) # create query to select the next row based on count field thisid = int(feature[0]) expression = 'count = ' + str(thisid + 1) exp2 = expression.replace("'", "")
def pantonext(): mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] lyr = arcpy.mapping.ListLayers( mxd, pythonaddins.GetSelectedTOCLayerOrDataFrame())[0] with arcpy.da.SearchCursor(lyr, ["FID"]) as features: for feature in features: # create query and select the next row based on the "count" field nextid = int(feature[0]) + 1 expression = 'FID = ' + str(nextid) exp2 = expression.replace("'", "") arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", exp2) # move map view to centre on the next point at the same scale as is currently being used scalenow = df.scale df.extent = lyr.getSelectedExtent() df.scale = scalenow arcpy.RefreshActiveView()
def onMouseDownMap(self, x, y, button, shift): blockgroups = pythonaddins.GetSelectedTOCLayerOrDataFrame() if not blockgroups: pythonaddins.MessageBox("Select the block groups layer.", "Info", 0) return self.x = x self.y = y self.layer = blockgroups sr = arcpy.SpatialReference(arcpy.Describe(blockgroups.name).spatialReference.factoryCode) pt = arcpy.PointGeometry(arcpy.Point(x, y), sr) arcpy.SelectLayerByLocation_management(blockgroups.name, "WITHIN_A_DISTANCE", pt, search_distance=0.0001, selection_type='ADD_TO_SELECTION') aa = arcpy.Describe(blockgroups.name) ss = aa.FIDset selectRow = ss.split(';') self.sRow = selectRow
def movepoint(clickedx, clickedy): mxd = arcpy.mapping.MapDocument("CURRENT") lyr = arcpy.mapping.ListLayers( mxd, pythonaddins.GetSelectedTOCLayerOrDataFrame())[0] # create cursor for selected point with arcpy.da.UpdateCursor( lyr, [movecount, newx, newy, "SHAPE@X", "SHAPE@Y", decidefield ]) as features: for feature in features: # update X and Y geometry fields (these are the LOCATION of the point, not written in the attribute table) # move point to the X,Y of the user's click feature[1] = clickedx feature[2] = clickedy feature[3] = clickedx feature[4] = clickedy feature[0] += 1 feature[5] = "moved" features.updateRow(feature) # refresh map view to show new point arcpy.RefreshActiveView()
def onSelChange(self, selection): floder = pythonaddins.OpenDialog("please select a floder", False, r"D:\test", "Save") self.mxd = arcpy.mapping.MapDocument('current') layer = pythonaddins.GetSelectedTOCLayerOrDataFrame() if isinstance(layer, arcpy.mapping.Layer): #arcpy.MakeFeatureLayer_management(layer, "lyr") icursor = arcpy.SearchCursor(layer) for row in icursor: igetvalue = row.getValue(selection) print "selection:", selection print "igetvalue:", igetvalue print """ "%s" = '%s' """ % (selection, igetvalue) arcpy.SelectLayerByAttribute_management( layer, "NEW_SELECTION", """ "%s" = '%s' """ % (selection, igetvalue)) save_name = igetvalue + ".shp" outsave = os.path.join(floder, save_name) arcpy.CopyFeatures_management(layer, outsave) arcpy.SelectLayerByAttribute_management( layer, "CLEAR_SELECTION")
def LocationCopy(): # get the current map document and the layer currently selected in TOC mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] lyr = arcpy.mapping.ListLayers( mxd, pythonaddins.GetSelectedTOCLayerOrDataFrame())[0] try: matchcount = len(lyr.getSelectionSet()) except Exception as e1: # error message if a layer and a row within that layer are not both selected pythonaddins.MessageBox(str(e1), "Error: select both layer and row", {0}) else: # check that only one row is selected if matchcount == 1: # create search cursor for selected point (read only) with arcpy.da.SearchCursor(lyr, ["SHAPE@X", "SHAPE@Y"]) as features: for feature in features: # copy coordinates of point try: lx = str(feature[0]) ly = str(feature[1]) # swap lx ly to fit lat/long format in JRC Global Surface Water Explorer location_text = ly + " " + lx command = "echo " + location_text + " | clip" i = subprocess.check_call(command, shell=True) # message for successful coping pythonaddins.MessageBox(location_text, "copied to clipboard", 0) except Exception as e2: # error message if unexpected errors pythonaddins.MessageBox(str(e2), "Error: coping location", 0) else: # error message if multiple rows are selected pythonaddins.MessageBox("more than one row selected", "Error", {0})
def verifySqueeSAR(): """ This function verifies if the selected layer is a SqueeSAR layer, and if the data is available. Returns: layer (Layer): selected layer or data frame from the table of contents. md (MapDocument): reference to current map document. Raises: UserWarning: if an invalid layer is selected. """ # Select current map # NOTE: To use the CURRENT keyword within a script tool, background # processing must be disabled. Background processing runs all scripts as # though they were being run as stand-alone scripts outside an ArcGIS # application, and for this reason, CURRENT will not work with background # processing enabled. There is a new script tool option called Always run # in foreground that ensures that a script tool will run in the foreground # even if background processing is enabled. md = ap.mapping.MapDocument("CURRENT") layer = pa.GetSelectedTOCLayerOrDataFrame() # Check if a layer is selected if not layer: pa.MessageBox("Select the SqueeSAR layer from the table of content\n" + "then select an area to evaluate the residual", "Warning", 0) raise UserWarning("Invalid layer!") # TODO: More tests should be added to verify if: # - the selected layer is an squeesar layer return (layer, md)
def resetpoint(): mxd = arcpy.mapping.MapDocument("CURRENT") lyr = arcpy.mapping.ListLayers( mxd, pythonaddins.GetSelectedTOCLayerOrDataFrame())[0] with arcpy.da.UpdateCursor(lyr, [ "count", decidefield, newx, newy, "SHAPE@X", "SHAPE@Y", "longitude", "latitude", movecount ]) as features: for feature in features: # set decision field and new x,y attribute fields to null feature[1] = None feature[2] = None feature[3] = None # set geometry attributes to X,Y coordinates based on attribute table feature[4] = feature[6] feature[5] = feature[7] # reset count of # of times feature has been moved to 0 feature[8] = "0" features.updateRow(feature) # thisid = int(feature[0]) # expression = 'count = ' + str(thisid) # exp2 = expression.replace("'", "") # arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", exp2) arcpy.RefreshActiveView()
def onClick(self): layer = pythonaddins.GetSelectedTOCLayerOrDataFrame() print(layer) clear(layer)
def onMouseDownMap(self, x, y, button, shift): Listvars.items = [] a = pythonaddins.GetSelectedTOCLayerOrDataFrame() gdbpath = self.get_geodatabase_path(a.workspacePath) # message = "Your mouse clicked \n longitud: " + str(x) + ", \n Latitud: " + str(y) + "\n And your selected \\ # layer is: " + a.name + "\n Located in gdb: " + a.workspacePath + "\n And GDB PATH is: " + gdbpath # pythonaddins.MessageBox(message, "My Coordinates") varpath = gdbpath + r'\1_VARIABLES.gdb' listFC = [] dts = [] ft = [] ruta, nombre_gdb=os.path.split(a.workspacePath) if os.path.exists(varpath): # pythonaddins.MessageBox(varpath, "GDB for Variables") arcpy.env.workspace = r''+varpath print arcpy.env.workspace listFC = arcpy.ListFeatureClasses(wild_card="V_*") ras = arcpy.ListRasters(wild_card="V_*") dt = arcpy.ListDatasets() for d in dt: ft = arcpy.ListFeatureClasses(wild_card="V*", feature_type = 'All', feature_dataset = d) dta= [d + '\\' + f for f in ft] dts.extend(dta) listFC.extend(ft) listFC.extend(ras) dts.extend(ras) # pythonaddins.MessageBox(listFC, "Variables") # pythonaddins.MessageBox(dts, "Variables") elif os.path.exists(gdbpath + r'\1_VARIABLE.gdb'): varpath = r''+ gdbpath + r'\1_VARIABLE.gdb' arcpy.env.workspace = varpath # print arcpy.env.workspace listFC = arcpy.ListFeatureClasses(wild_card="V_*") ras = arcpy.ListRasters(wild_card="V_*") dt = arcpy.ListDatasets() for d in dt: ft = arcpy.ListFeatureClasses(wild_card="V*", feature_type = 'All', feature_dataset = d) dta = [d + '\\' + f for f in ft] dts.extend(dta) listFC.extend(ft) listFC.extend(ras) dts.extend(ras) elif os.path.exists(r''+ gdbpath[0:-12] + r'\1_VARIABLE\{}'.format(nombre_gdb)): varpath = r''+ gdbpath + r'\..\1_VARIABLE\{}'.format(nombre_gdb) arcpy.env.workspace = varpath # print arcpy.env.workspace listFC = arcpy.ListFeatureClasses(wild_card="V_*") ras = arcpy.ListRasters(wild_card="V_*") dts = listFC dt = arcpy.ListDatasets() listFC.extend(ras) dts.extend(ras) elif os.path.exists(r''+ gdbpath[0:-12] + r'\1_VARIABLES\{}'.format(nombre_gdb)): varpath = r''+ gdbpath[0:-12] + r'\1_VARIABLES\{}'.format(nombre_gdb) arcpy.env.workspace = varpath #print arcpy.env.workspace listFC = arcpy.ListFeatureClasses(wild_card="V_*") ras = arcpy.ListRasters(wild_card="V_*") dts = listFC dt = arcpy.ListDatasets() listFC.extend(ras) dts.extend(ras) else: r = r''+ gdbpath[0:-12] + r'\1_VARIABLES\{}'.format(nombre_gdb) pythonaddins.MessageBox("GDB for Variables don't exist"+r, "Error GDB is not present in route") Listvars.refresh() for layer in dts: Listvars.items.append(layer) self.x = x self.y = y tool.deactivate() pass