POST
|
I am looking for a way to identify what layers have a selection in the TOC. I know this can be done in .NET. I have yet to see anything in python. If anyone can help let me know! Thank You, - B Hi Bob, It would be nice to have a short way of determining if a layer in the TOC has a selection (which is pretty straightforward with ArcObjects). I wrote a small piece of code and it seams to work as long as not all the features in a layer are selected: import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "")[0]
lyrs = arcpy.mapping.ListLayers(mxd, "", df)
for lyr in lyrs:
if lyr.isFeatureLayer:
# this is the number of (selected) features in layer in TOC (in DefQuery)
countSel = int(arcpy.GetCount_management(lyr).getOutput(0))
# when there is a defintionQuery test features in query against 'selected' feature
lyr2 = lyr.dataSource
if lyr.definitionQuery == '':
countDefQ = int(arcpy.GetCount_management(lyr2).getOutput(0))
else:
field = "OID@"
countDefQ =0
for row in arcpy.da.SearchCursor(lyr2, (field),where_clause=lyr.definitionQuery):
countDefQ+=1
# now test the counts
if countSel == countDefQ:
print "Layer '{0}' has no selection OR all features are selected".format(lyr.name)
else:
print "Layer '{0}' has a selection. CountSel={1} en CountDefQ={2}".format(lyr.name,countSel,countDefQ) I came across a much smaller snippet of Python code in an older post: import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "")[0]
lyrs = arcpy.mapping.ListLayers(mxd, "", df)
for lyr in lyrs:
if lyr.isFeatureLayer:
selectionCount2 = int(arcpy.GetCount_management(arcpy.Describe(lyr).catalogpath).getOutput(0)) - int(arcpy.GetCount_management(lyr).getOutput(0))
if selectionCount2 == 0:
print "Layer '{0}' has no selection OR all features are selected".format(lyr.name)
else:
print "Layer '{0}' has a selection. Difference={1}".format(lyr.name,selectionCount2) The downside of this method is that it doesn't take the Definition Query into account. Maybe if both are mixed it can be done. I think this would be a nice feature to have in a next release... Kind regards, Xander Bakker
... View more
10-10-2013
12:59 AM
|
0
|
0
|
236
|
POST
|
Thanks Xander for the insights. Looks like I won't be able to do exactly what I was hoping to do, but perhaps the Layer.visible check will allow me to create a close work-around. Thanks Jeffrey as well. I had looked into the GetSelectedTOCLayerOrDataFrame() method, but as Xander says, it doesn't work when multiple layers are selected. Tom
... View more
10-10-2013
04:28 PM
|
0
|
0
|
882
|
POST
|
I am going to blame this on sleep deprivation from staying up with the my kids. I finally realized what you said in your first reply and switched from using the old arcpy.UpdateCursor and used the arcpy.da.UpdateCursor instead. Then I used the parameters in the correct order and the tool worked fine.
# Import arcpy and date time module
import arcpy
import datetime
# Local variables:
today = datetime.date.today()
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
ProjectTracking = arcpy.mapping.ListLayers(mxd, "PlanningProjectTracking", df) [0]
# Geting user input for project name, status, type, submital date and planner name
ProjectName = arcpy.GetParameterAsText(0)
ProjStatus = arcpy.GetParameterAsText(2)
SubmitDate = arcpy.GetParameterAsText(1)
DevelopeType = arcpy.GetParameterAsText(3)
PlannerName = arcpy.GetParameterAsText(4)
#Set variable to hold SQL statement to query out project to update
whereClause = "[ProjectName] = '{0}'".format(ProjectName)
#Used update cursor to create update project tracking records.
Ucursor = arcpy.da.UpdateCursor(ProjectTracking,["PROJECTNAME","STATUS","SUBMITTALDATE","DEVELOPEMENTTYPE","PLANNER","EDITDATE"],whereClause)
for row in Ucursor:
irow = (ProjectName,ProjStatus,SubmitDate,DevelopeType,PlannerName,today)
Ucursor.updateRow(irow)
arcpy.RefreshActiveView()
... View more
09-25-2013
01:44 PM
|
0
|
0
|
2342
|
POST
|
You made three errors. Xander pointed out one, which is that you put the result on the same line as the else clause rather than on a new line. The second it that at 10.0 you should not use Dim statements. VBA is gone and in VB script all variables are Variant and can no longer be defined, so don't bother with them or just put Dim codigo and nothing else. The third is that you closed the If block with EndIf (one word) and not End If (two words). Assuming there are no null values in your data and your field is long enough to handle the largest value stored in the CAMPO field this code will work (with codigo being put in the field text box as you indicated): If [CAMPO] = "Captura" OR [CAMPO] = "Replanteo" OR [CAMPO] = "GPS" Then
codigo = "1"
ElseIf [CAMPO] = "Plano" OR [CAMPO] = "Ortofoto" Then
codigo = "2"
ElseIf [CAMPO] = "Catastro" OR [CAMPO] = "Ajuste parcelario" Then
codigo = "3"
Else
codigo = [CAMPO]
End If
... View more
09-09-2013
07:09 AM
|
0
|
0
|
209
|
POST
|
Hi Gludo and Elisabeth, I think you can use some Python to achieve this. See example below: def main():
import arcpy
# assume data is available as point featureclass
# and fc has projected coordinate system
fc = "c:/folder/yourGeodatabase.gdb/yourFCname" # change this (path to featureclass GPS points)
fldDistance = "DistGPSpoints" # change this (output name distance field)
# add distance field if it doesn't exist
if FieldExist(fc,fldDistance) == False:
arcpy.AddField_management(fc, fldDistance, "DOUBLE")
# Create update cursor for feature class
fields = ['SHAPE@XY', fldDistance]
with arcpy.da.UpdateCursor(fc, fields) as cursor:
X = 0
Y = 0
cnt = 0
for row in cursor:
cnt+=1
prevX = X
prevY = Y
X = row[0][0]
Y = row[0][1]
if cnt == 1:
# for first point distance is 0
distance = 0
else:
distance = getDist(X,Y,prevX,prevY)
# Update row
row[1] = distance
cursor.updateRow(row)
del row
def getDist(X1,Y1,X2,Y2):
import math
return math.hypot(X2 - X1, Y2 - Y1)
def FieldExist(featureclass, fieldname):
import arcpy
fieldList = arcpy.ListFields(featureclass, fieldname)
fieldCount = len(fieldList)
if (fieldCount == 1):
return True
else:
return False
if __name__ == '__main__':
main()
You will need to change the path to the featureclass and the name of the output field. It assumes the data is available as point featureclass and the point should be projected (not in a geographic coordinate system). The script will: add the output distance field (now named "DistGPSpoints") if it doesn't exist yet loop through the points and calculate the distance to the previous point Kind regards, Xander
... View more
10-29-2013
12:51 AM
|
0
|
0
|
486
|
POST
|
with arcpy.da.UpdateCursor(FClassOrTable, fields) as cursor:
for row in cursor:
row[1] = GetMmax(row[0]) Instead of using a function to breakdown that Mmax value, you could also just use the extent object, which comes as part of the Shape@. Like this: with arcpy.da.UpdateCursor(FClassOrTable, fields) as cursor:
for row in cursor:
row[1] = row[0].extent.MMax
... View more
12-03-2014
08:10 AM
|
0
|
0
|
465
|
POST
|
Hi Zuoqi Chen, Having a dataset locked can be a difficult thing to solve. IMHO I thing the locking mechanism in ArcGIS has been implemented to drastic, causing more problems than it avoids... I assume you are writing your raster datasets to a file geodatabase. It is possible to test the scema locking before deleting and place it in a "try except" (as shown below), but this doesn't solve anything if you have a lock on your dataset. Always be sure to delete any references to your dataset and delete cursors, rows, etc...
if arcpy.TestSchemaLock(data):
try:
arcpy.Delete(data)
except:
# catch error here
else:
print "Unable to acquire schema lock"
source: http://resources.arcgis.com/en/help/main/10.2/index.html#/TestSchemaLock/018v0000002m000000/ What I have also come across is using the garbage collector. This may sometimes solve the problem. See snippet below:
# at beginning of script
import gc # Garbage Collector
gc.collect()
# at end of script
collected = gc.collect()
print "Garbage collector: collected %d objects." % (collected)
# try to delete now...
sources: http://gis.stackexchange.com/questions/19408/arcgis-10-0-python-searchcursor-file-locking http://docs.python.org/2/library/gc.html http://pymotw.com/2/gc/ If this doesn't work, you could go back to the gold old Esri grid data format (write raster to folder), which is probably one of the last formats for which the locking mechanism hasn't been implemented. 😄 This did solve some nasty locking problems I had...
... View more
09-03-2013
01:17 AM
|
0
|
0
|
651
|
POST
|
Hi, I�??d like to normalize map data in raster format to the data range using Raster Calculator. I'm not so much concerned with the accuracy of the method. e.g. v�??(i) = (v(i) - minA) / (maxA - minA) What is the syntax I need to do this? I am getting problems using the following script: ("raster" - min("raster")) / (max("raster") - min("raster")) Thanks! Hi, If I could convince you to do this in the Python Window, it would be a lot easier. In that case you can make use of the Raster object in arcpy. Just have a look at the code below: import arcpy
my_raster = arcpy.Raster(r'obj\objecten')
result = (my_raster - my_raster.minimum) / (my_raster.maximum - my_raster.minimum)
Basically you load the arcpy module, you define a variable "my_raster" to which you will assign the raster you want to process. In this case I used a raster called "objecten" which resides in a grouplayer called "obj", but you can just specify the name of the raster as it is called in your table of content. The last line performs the calculation (make sure you have the Spatial Analyst extension switched on). As you can see you can access the minimum and maximum values of a raster, since they are properties of the raster object. See also: http://resources.arcgis.com/en/help/main/10.1/index.html#//002100000017000000 http://resources.arcgis.com/en/help/main/10.1/index.html#//018z00000051000000 To save the result, you can add another line:
result.save('yourNameGoesHere')
It will save it in your current workspace. Hope this helps you. Kind regards, Xander
... View more
09-03-2013
04:22 AM
|
0
|
0
|
255
|
POST
|
Its weird how the in program label expression builder when set to Python still uses [XYZ] for the fields. (in ArcMap 10.3) Thanks, I wasn't aware of the startswith method, the code works now as: def FindLabel ( [SITE] 😞 if str([SITE]).startswith('18') == True: return " " else: return [SITE]
... View more
07-23-2018
06:37 AM
|
1
|
0
|
2785
|
POST
|
Hi Anne, The "Error 000622" is referring to invalid parameters for the tool. In this case due to the fact that you specify the list of tables in the MakeXYEventLayer tool, rather than the table itself. Please observe the code below: tables = arcpy.ListTables()
for tbl in tables:
arcpy.MakeXYEventLayer_management(tbl, xc, yc, out_layer, spRef)
"tables" is a variable with the list of tables found in the current workspace then you do a for loop, accessing each table "tbl" in the list "tables" specify the variable "tbl" (the single table) to be used in the MakeXYEventLayer tool Another thing to remember is that you use your latitude as X-coord and you Longitude as Y-coord. This should be the other way around: xc = "long"
yc = "Lat" Kind regards, Xander
... View more
02-18-2014
03:12 AM
|
0
|
0
|
170
|
POST
|
One thing that I would advise, in case there is any doubt about how the parameters should be provided, is to execute the tool manually and copy the python code from the Results window. This shows how the parameters should be provided. In case you feel that the help does not reflect clearly how things the tool should be used, you can use the "Feedback on this topic" link in the lower right part of the Help topic. I have used it several times and Esri has responded very fast (mostly the same day).
... View more
09-28-2015
05:04 AM
|
1
|
0
|
248
|
POST
|
Try this, I think it's just a window size problem. ArcToolbox - Missing box - YouTube
... View more
10-18-2014
08:55 PM
|
0
|
0
|
574
|
POST
|
I agree that I wasn't too keen on having to "consume the iterable" and reset it. I had tried the .next() approach and got the StopIteration error but wasn't quite sure how to handle it; thank you Bruce Harold for mentioning that. That last option with row = None is clever and seems to solve both problems; thanks for sharing.
... View more
08-26-2016
03:11 PM
|
0
|
0
|
162
|
Title | Kudos | Posted |
---|---|---|
1 | 11-12-2017 02:40 PM | |
1 | 11-14-2013 10:56 PM | |
1 | 05-22-2019 01:11 PM | |
1 | 06-28-2019 02:45 PM | |
2 | 07-27-2022 02:21 PM |
Online Status |
Offline
|
Date Last Visited |
a month ago
|