|
POST
|
I'm not sure that your try/except is doing what is expected. The way the code is set up, it appears to be generating an error on the first Intersect_analysis, possibly an error the second, and then setting the variable to "the Main". If you don't need to create a "PipeExposure_Intersect" layer, you might try something like: # select main intersects
arcpy.SelectLayerByLocation_management("pipeExposure", "INTERSECT", "Main")
main_item = [r[0] for r in arcpy.da.SearchCursor('pipeExposure',['OID@'])]
# select service intersects
arcpy.SelectLayerByLocation_management("pipeExposure", "INTERSECT", "Service")
service_item = [r[0] for r in arcpy.da.SearchCursor('pipeExposure',['OID@'])]
# clear any selections in pipeExposure layer
arcpy.SelectLayerByAttribute_management("pipeExposure", "CLEAR_SELECTION")
# results - can use an update cursor if updating attributes
with arcpy.da.SearchCursor("pipeExposure",["OID@"]) as cursor:
for row in cursor:
if row[0] in main_item:
print("{} MAIN".format(row[0]))
elif row[0] in service_item:
print("{} SERVICE".format(row[0]))
else:
print("{} N/A".format(row[0]))
You will have 2 lists of main/service lines by line 12 and may not need the additional code.
... View more
09-20-2020
04:38 PM
|
0
|
2
|
1226
|
|
POST
|
You should be able to use the ArcGIS REST API Add Features to accomplish the task. The basic steps would be to use a SearchCursor to read the data from your geodatabase, construct a json object of the features to transfer, then use Add Features to add the items to your hosted feature. You can also use the ArcGIS API for Python. See Append Features for more information. Also, the FeatureLayer.edit_features may be of interest.
... View more
09-14-2020
08:56 PM
|
0
|
1
|
7094
|
|
POST
|
Shouldn't line 5 come before line 2 where pLocation is referenced?
... View more
09-10-2020
11:24 AM
|
2
|
4
|
2813
|
|
POST
|
The { and } characters in the filename are not valid. You need to remove them or provide a different file name.
... View more
09-10-2020
10:25 AM
|
1
|
1
|
2813
|
|
POST
|
Here is some test code for geometry methods .within and .distanceTo. import arcpy
# IMPORTANT: all geometry should be in same projection
KMile = 1609.34
def ptGeo(geoResult):
ptGeometry = arcpy.PointGeometry(arcpy.Point(
geocodeResult["candidates"][0]["location"]["x"],
geocodeResult["candidates"][0]["location"]["y"]),
arcpy.SpatialReference(geocodeResult["spatialReference"]["wkid"]))
return ptGeometry
# feature class contains only one feature, polygon outline of Virginia in UTM Zone 17N (spatial ref: 26917)
va = r'C:\Path\to\Test.gdb\Virginia'
# easy way to get Virginia geometry
vaGeo = arcpy.da.SearchCursor(va,"SHAPE@").next()[0]
# paired address point and geocoding results
points = [['1520 Split Oak Ln, Henrico, VA, 23229',
{u'candidates': [{u'attributes': {}, u'score': 100, u'location': {u'y': 4167142.8740720972, u'x': 805193.5919402852}, u'address': u'1520 SPLIT OAK LN, HENRICO, VA, 23229'}], u'spatialReference': {u'wkid': 26917, u'latestWkid': 26917}}],
['439 Rockford St, Mt Airy, NC 27030',
{u'candidates': [{u'attributes': {}, u'score': 100, u'location': {u'y': 4038943.928205234, u'x': 533895.533587685}, u'address': u'27030'}], u'spatialReference': {u'wkid': 26917, u'latestWkid': 26917}}]
]
for address, geocodeResult in points:
pt = ptGeo(geocodeResult)
if pt.within(vaGeo):
print("Location is within Virginia: {}".format(address))
else:
miles = pt.distanceTo(vaGeo)/KMile
print("Location is {:.1f} miles outside Virginia: {}".format(miles, address))
# output
# Location is within Virginia: 1520 Split Oak Ln, Henrico, VA, 23229
# Location is 4.3 miles outside Virginia: 439 Rockford St, Mt Airy, NC 27030
''' methods:
within (second_geometry, {relation})
Indicates if the base geometry is within the comparison geometry.
distanceTo (other)
Returns the minimum distance between two geometries. If the geometries intersect, the minimum distance is 0.
Both geometries must have the same projection.
'''
... View more
09-09-2020
05:45 PM
|
2
|
1
|
1198
|
|
POST
|
You should be able to specify a spatial reference in your geometry on line 42: geometry_dict = dict(y = x['lat'], x = x['lng'], spatialReference = dict(wkid = 4326))
# {'y': 39.948874, 'x': -75.948874, 'spatialReference': {'wkid': 4326}} You could also try .projectAs: import arcpy
def project(x,y): # lon,lat to web mercator
# WGS 1984 : (4326) Lat/Lon
# WGS 1984 Web Mercator (auxiliary sphere) : (102100) or (3857)
ptGeometry = arcpy.PointGeometry(arcpy.Point(x,y),arcpy.SpatialReference(4326)).projectAs(arcpy.SpatialReference(3857))
return (ptGeometry.firstPoint.X, ptGeometry.firstPoint.Y)
print(project(-75.948874, 39.948874))
# result: (-8454589.980002495, 4858515.567532215)
... View more
09-09-2020
12:25 PM
|
0
|
1
|
1739
|
|
POST
|
Another approach... The Spatial Join (Analysis) will compute distances in certain cases. As a test, a Virginia layer (containing only one feature - an outline of the state in UTM Zone 17N) was opened in Desktop 10.5. I geocoded the two addresses previously used with some others that lie in and outside the state. I pasted code into the Python window, ran the spatial join and had the following results: The DistanceTo field was generated by the spatial join. A distance of 0 indicates the point is inside the state. If it lies outside, a distance in meters is calculated. This distance can be compared to the buffer in the Distance field. If the DistanceTo is less than the Distance buffer, the point is within the buffer. A select layer by attribute can use this in a where clause. Here's the test code, which may need modification depending on your settings or if run outside ArcMap. In_memory was used in creating the points and spatialJoin layers, so they should be deleted at some point. import arcpy, requests, json
# ['searchAddress', searchDistance (in miles)],
addressList = [['1520 Split Oak Ln, Henrico, VA, 23229', 25],
['6188 Maddox Blvd, Chincoteague, VA, 23336', 12],
['318 Market St, Peterstown, WV 24963', 1],
['109 Federal St, Rich Creek, VA 24147',1],
['439 Rockford St, Mt Airy, NC 27030',2] ]
KMile = 1609.34
def singleAdressGeocode(address):
geoCodeUrl = r"https://gismaps.vita.virginia.gov/arcgis/rest/services/Geocoding/VGIN_Composite_Locator/GeocodeServer/findAddressCandidates"
outSR = "26917"
r = requests.get(geoCodeUrl, params={'SingleLine': address, 'outSR' : outSR, 'maxLocations': 1, 'f': 'pjson'}) # requests will url encode params
data = r.json()
if data["candidates"]:
return data
else:
return None # indicates error
def insertResult(address, distance, result, cursor):
geoAddress = geocodeResult["candidates"][0]["address"]
score = geocodeResult["candidates"][0]["score"]
pointX = geocodeResult["candidates"][0]["location"]["x"]
pointY = geocodeResult["candidates"][0]["location"]["y"]
ptGeometry = arcpy.PointGeometry(arcpy.Point(
geocodeResult["candidates"][0]["location"]["x"],
geocodeResult["candidates"][0]["location"]["y"]),
arcpy.SpatialReference(geocodeResult["spatialReference"]["wkid"]))
cursor.insertRow([ptGeometry, address, geoAddress, score, pointX, pointY, distance])
# create in_memory feature to save address points
fc = arcpy.CreateFeatureclass_management("in_memory","points","POINT", spatial_reference=arcpy.SpatialReference(26917))
arcpy.AddField_management(fc,'Address','TEXT',"#","#",100,'Address',"NULLABLE","NON_REQUIRED")
arcpy.AddField_management(fc,'geoAddress','TEXT',"#","#",100,'Geocoded Address',"NULLABLE","NON_REQUIRED")
arcpy.AddField_management(fc,'geoScore','Double',"#","#","#",'Geocode Score',"NULLABLE","NON_REQUIRED")
arcpy.AddField_management(fc,'POINT_X','Double',"#","#","#",'Point X',"NULLABLE","NON_REQUIRED")
arcpy.AddField_management(fc,'POINT_Y','Double',"#","#","#",'Point Y',"NULLABLE","NON_REQUIRED")
arcpy.AddField_management(fc,'Distance','Double',"#","#","#",'Distance',"NULLABLE","NON_REQUIRED")
# start an insert cursor
cursor = arcpy.da.InsertCursor(fc,["SHAPE@", 'Address', 'geoAddress', 'geoScore', 'POINT_X', 'POINT_Y', 'Distance'])
# loop through addresses and insert in points feature
for address, distance in addressList:
geocodeResult = singleAdressGeocode(address)
if geocodeResult:
insertResult(address, int(distance)*KMile, geocodeResult, cursor)
else:
print('ERROR: Address ({}) did not geocode'.format(address))
del cursor # done with insert cursor
# a spatial join can be used to compute distances
# Virginia layer contains only 1 feature, an outline of VA using NAD_1983_UTM_Zone_17N
# field_mapping is optional, only fields in points feature were used
arcpy.SpatialJoin_analysis(target_features="points",
join_features="Virginia",
out_feature_class="in_memory/spatialJoin",
join_operation="JOIN_ONE_TO_ONE",
join_type="KEEP_ALL",
field_mapping='''
Address "Address" true true false 100 Text 0 0 ,First,#,points,Address,-1,-1;
geoAddress "Geocoded Address" true true false 100 Text 0 0 ,First,#,points,geoAddress,-1,-1;
geoScore "Geocode Score" true true false 0 Double 0 0 ,First,#,points,geoScore,-1,-1;
POINT_X "Point X" true true false 0 Double 0 0 ,First,#,points,POINT_X,-1,-1;
POINT_Y "Point Y" true true false 0 Double 0 0 ,First,#,points,POINT_Y,-1,-1;
Distance "Distance" true true false 0 Double 0 0 ,First,#,points,Distance,-1,-1''',
match_option="CLOSEST_GEODESIC",
distance_field_name="DistanceTo")
# a search cursor can print a results table
fields = ['Address', 'geoAddress', 'geoScore', 'POINT_X', 'POINT_Y', 'Distance', 'DistanceTo']
print('\t'.join(fields)+'\tLocation')
with arcpy.da.SearchCursor("spatialJoin", fields) as cursor:
for a, g, s, x, y, d, dt in cursor:
if dt == 0:
inout = 'Inside Virginia'
elif dt < d:
inout = 'Within Buffer'
else:
inout = 'Outside Buffer'
print('{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(a, g, s, x, y, d, dt, inout))
# delete the in_memory feature when done
# arcpy.Delete_management('in_memory/points')
# arcpy.Delete_management('in_memory/spatialJoin')
''' # address points can be selected where the distance is greater than the buffer
arcpy.SelectLayerByAttribute_management(in_layer_or_view="spatialJoin",
selection_type="NEW_SELECTION",
where_clause="DistanceTo > Distance")
''' Hope this helps.
... View more
09-07-2020
09:24 PM
|
2
|
0
|
1198
|
|
POST
|
The ptGeometry item should have a spatial reference; it should not be null (Line 7 in the first code block in your previous message). I think the first parameter in SelectLayerByLocation should be a feature layer, and ptGeometry (which is only geometry for a point) is not a feature. I have been experimenting with some code in the Python window of Desktop 10.5 that may help you get the geocoding address coordinates into point geometry and then into a feature. The test code did create a point feature and it appears to be correctly located using the Streets basemap (and Google Maps). Here's my test code: # create the point geometry
address: 1520 Split Oak Ln, Henrico, VA, 23229
distance: 25
>>> geocodeResult
{u'candidates': [{u'attributes': {}, u'score': 100, u'location': {u'y': 4167142.8740720972, u'x': 805193.5919402852}, u'address': u'1520 SPLIT OAK LN, HENRICO, VA, 23229'}], u'spatialReference': {u'wkid': 26917, u'latestWkid': 26917}}
>>> addressResult = geocodeResult["candidates"][0]["address"]
>>> addressResult
u'1520 SPLIT OAK LN, HENRICO, VA, 23229'
>>> ptGeometry = arcpy.PointGeometry(arcpy.Point(
... geocodeResult["candidates"][0]["location"]["x"],
... geocodeResult["candidates"][0]["location"]["y"]),
... arcpy.SpatialReference(geocodeResult["spatialReference"]["wkid"]))
...
>>> ptGeometry.JSON
u'{"x":805193.59194028517,"y":4167142.8740720972,"spatialReference":{"wkid":26917,"latestWkid":26917}}'
>>>
# create an in_memory feature class to hold the point
>>> fc = arcpy.CreateFeatureclass_management("in_memory","points","POINT",
... spatial_reference=arcpy.SpatialReference(geocodeResult["spatialReference"]["wkid"]))
...
>>> fc
<Result 'in_memory\\points'>
>>> cursor = arcpy.da.InsertCursor(fc,["SHAPE@"])
>>> cursor.insertRow([ptGeometry])
1L
>>> del cursor
# delete the in_memory feature when done
>>> arcpy.Delete_management('in_memory/points')
<Result 'true'>
... View more
09-04-2020
12:13 AM
|
0
|
2
|
5182
|
|
POST
|
Regarding testing the new layer: I was unable to turn ptGeometry into a layer as you are attempting to do in line 2 of your last code segment. However, I was able to use ptGeometry as the select_features parameter in Select Layer By Location. To test the values being used for x and y, you can print the JSON containing the x and y values: # x,y for 6188 Maddox Blvd, Chincoteague, VA, 23336
x = -77.434769 # longitude
y = 37.541290 # latitude
ptGeometry = arcpy.PointGeometry(arcpy.Point(x,y),arcpy.SpatialReference(4326)).projectAs(arcpy.SpatialReference(26917))
print(ptGeometry.JSON)
''' Output:
{"x":815010.20711794402,"y":4160898.4941948522,"spatialReference":{"wkid":26917,"latestWkid":26917}}
''' I am a bit confused with your state layer, buffer and distance. Does the layer have only one feature, the state of Virginia? Or does it contain other states or Virginia counties. Is the buffer being used to see if the address is close to the border of Virginia, possibly in a nearby state?
... View more
09-03-2020
12:14 PM
|
0
|
4
|
1970
|
|
POST
|
I assume BufferGeom is the polygon layer, so perhaps something like: x = -75.369027 # longitude
y = 37.935822 # latitude
# WGS 1984: 4326
# GCS North American 1983: 4269 ## use the factory/authority code for BufferGeom layer
ptGeometry = arcpy.PointGeometry(arcpy.Point(x,y),arcpy.SpatialReference(4326)).projectAs(arcpy.SpatialReference(4269))
results = arcpy.SelectLayerByLocation_management('IN_MEMORY/BufferGeom', 'CONTAINS', ptGeometry, selection_type="NEW_SELECTION")
... View more
09-02-2020
04:55 PM
|
0
|
8
|
3212
|
|
POST
|
Per Duncan Hornby comment You typically drill down to the FeatureClass. Could you have 2 parameters, the first being a multiValue list of items to copy, and the second is the save location? def getParameterInfo(self):
"""Define parameter definitions"""
gdbFeatures = arcpy.Parameter(
displayName = "Select items to copy",
name = "gdbFeatures",
datatype = ["DEFeatureClass", "DEFeatureDataset", "DETable"],
parameterType = "Required",
direction = "Input",
multiValue = True)
gdbSave = arcpy.Parameter(
displayName = "Select save location (geodatabase)",
name = "gdbSelect",
datatype = "DEWorkspace", # perhaps DEGeoDataServer for enterprise server ?
parameterType = "Required",
direction = "Input")
return [gdbFeatures, gdbSave]
... View more
08-28-2020
10:00 PM
|
1
|
0
|
1559
|
|
POST
|
Joshua Bixby If the goal is to keep the letter and drop the zero from the next to last position, shouldn't line 9 be ("not" isdigit) ? wpin = "{}{}{}".format(i, j if not j.isdigit() else " ", k)
... View more
08-28-2020
09:39 PM
|
1
|
1
|
1017
|
|
POST
|
A quick example (using underscore for space): rows = [['W1234500000',],
['W1234501000',],
['W12345010S0',],
['W12345010S1',] ]
for row in rows:
if row[0][10] == '0':
print(row[0][:9]+"_"+row[0][-1:])
else:
print(row[0])
prints:
W12345000_0
W12345010_0
W12345010_0
W12345010S1
... View more
08-28-2020
12:40 PM
|
0
|
1
|
2109
|
|
POST
|
If you wish to use IDLE (2.7.16), there is an old script here: how to get token to access a map service or feature service?
... View more
08-25-2020
12:28 PM
|
0
|
2
|
5955
|
| Title | Kudos | Posted |
|---|---|---|
| 1 | 10-27-2016 02:23 PM | |
| 1 | 09-09-2017 08:27 PM | |
| 2 | 08-20-2020 06:15 PM | |
| 1 | 10-21-2021 09:15 PM | |
| 1 | 07-19-2018 12:33 PM |
| Online Status |
Offline
|
| Date Last Visited |
09-15-2025
02:54 PM
|