POST
|
This is what I use: #note: this must be run in Python 3.x
#This script will list all ArcGIS Online content, what it is, who owns it, the dates it was created & modified
import arcgis, time
import csv
gis=GIS(url,username,password)
print ("Organization Name: "+str(gis.properties.name))
print ("Portal Name: "+str(gis.properties.portalName))
#print ("URL: "+str(gis.properties.customBaseUrl))
print ("ArcGIS Online Credits Available: "+str("{:,}".format(gis.properties.availableCredits)))
print("ELA Expiration Date: "+str(time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(gis.properties.subscriptionInfo.expDate/1000.0))))
print("Max Users per Level: ")
for key,val in gis.properties.subscriptionInfo.maxUsersPerLevel.items():
print (key, "=", val)
print ("\n")
#set item_type if you only want to search for ex. "Feature Layer"
search_result = gis.content.search(query="", item_type="",max_items=10000) #max number is set so it will return more than the default 10 results
outCSVfile=r"L:\Scripts\ArcGISOnline\ArcGISOnline_ContentDetails.csv"
csvfile = open(outCSVfile, 'w',newline='')
writer = csv.writer(csvfile)
writer.writerow(["Title","ItemType","Sharing","Description","Snippet","Tags","Categories","AccessInformation","Protected","Status","OwnedBy","DateCreated","DateLastModified","View Count","Item_ID"])
print("There are: "+str(len(search_result))+" total items in our ArcGIS Online.")
recordNumber = 0
for i in search_result:
recordNumber+=1
try:
description = str(i.description.encode('unicode-escape').decode('utf-8')) #removes emojis
except:
description = str(i.description)
#print(i.title+","+","+i.type+","+i.access+","+description+str(i.snippet)+","+str(i.tags)+","+str(i.categories)+","+str(i.accessInformation)+","+str(i.protected)+","+str(i.content_status)+i.owner+","+","+str(time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(i.created/1000.0))+","+str(time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(i.modified/1000.0))))+","+str(i.numViews)+","+(i.id))
#print (recordNumber) # so we know the script is doing something
writer.writerow([i.title, i.type,i.access,description,str(i.snippet),str(i.tags),str(i.categories),str(i.accessInformation),str(i.protected),str(i.content_status),str(i.owner),str(time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(i.created/1000.0))),str(time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(i.modified/1000.0))),i.numViews,i.id])
csvfile.close()
... View more
3 weeks ago
|
1
|
1
|
118
|
POST
|
I add something like this if I want to remind myself that I'm about to edit or overwrite critical data... answer = input("Do you want to continue? (yes/no): ").lower()
if answer == "yes" or answer == "y":
print("Continuing...")
# Add your code here for further execution
else:
print("Exiting...")
sys.exit()
... View more
3 weeks ago
|
2
|
0
|
253
|
POST
|
Yes, that is correct. You need to use update cursor to edit records whereas a search cursor is only used for read-only.
... View more
a month ago
|
1
|
0
|
189
|
POST
|
To get unique values in a field, I've used. import arcpy
featureClass = r"C:\Default.gdb\Export_Output_10"
fields = ['FEATUREID']
listOfValues=[]
with arcpy.da.SearchCursor(featureClass, fields) as cursor:
for row in cursor:
listOfValues.append(row[0]) Then you can convert the list to a set. # set() to convert list to set
set_of_values = set(listOfValues) Sets can be subtracted from each other to find the differences. Python Set | difference() - GeeksforGeeks
... View more
03-14-2024
05:47 PM
|
0
|
0
|
175
|
POST
|
This is what I've used to loop through a directory of MXDs to examine and/or edit them... import os, arcpy
# set a directory you're interested in
workingDir = r'C:\Users\tlaue\Desktop\GISTutorial'
arcpy.env.overwriteOutput = True
# get a list of all the files in the directory
maps = os.listdir(workingDir)
for m in maps:
if m[-4:] == ".mxd":
mxd = arcpy.mapping.MapDocument(os.path.join(workingDir,m))
## DO SOMETHING HERE ##
mxd.save()
... View more
02-28-2024
12:29 PM
|
1
|
1
|
131
|
POST
|
I'm only aware of the arcpy command to not export attachments within Pro exports. arcpy.env.maintainAttachments = False Other than writing a script to delete all the attachments after they've been downloading, I'm curious what other's have found as a solution.
... View more
02-21-2024
09:13 AM
|
0
|
0
|
312
|
POST
|
@jzcgis wrote: Honestly, half of my workflow would be cut in half if ESRI would allow for multiple geocoders to be used when geocoding with the option to use your local one first and then anything not matched to use the ESRI geocoder. I have been using this methodology. I first try using one of thecounty Geolocators in our service territory. Then if no results are returned, I default back to the ESRI geolocator. def ESRIGeolocator(addressString):
## STEPS
# street address match check
# street name match check
# call map grid match
geocode_result = arcgis.geocoding.geocode(address=addressString, as_featureset=True)
#geocode_result = geocode(address=addressString, as_featureset=True)
resultNumber = 0
maxMatchScore = 0
matchScore = 0
bestMatchRecordNumber=-1
for geoResult in geocode_result.features:
while resultNumber<len(geocode_result.features):
#print("made it here")
match_type = geocode_result.features[resultNumber].attributes["Addr_type"]
matchAddress = geocode_result.features[resultNumber].attributes['Match_addr']
#print("\t"+matchAddress)
#print(match_type)
if match_type == "StreetAddress" or match_type == "PointAddress" :
#print("made it here")
#print(geocode_result.features[resultNumber])
matchScore = geocode_result.features[resultNumber].attributes["Score"]
if matchScore > maxMatchScore:
maxMatchScore = matchScore
bestMatchRecordNumber = resultNumber
## print(maxMachScore)
## print(bestMatchRecordNumber)
resultNumber +=1
if bestMatchRecordNumber!=-1 or maxMatchScore>93.1:
#print(bestMatchRecordNumber)
#print(matchScore)
#print(new_geocode_result.features[bestNewMatchRecordNumber])
longitude = geocode_result.features[bestMatchRecordNumber].geometry.x
latitude = geocode_result.features[bestMatchRecordNumber].geometry.y
bestMatchAddress = geocode_result.features[bestMatchRecordNumber].attributes['Match_addr']
#print(bestMatchAddress)
matchScore = geocode_result.features[bestMatchRecordNumber].attributes["Score"]
#print("\t"+str(matchScore)+"% geocode match")
matchType = geocode_result.features[bestMatchRecordNumber].attributes["Addr_type"]
#print("\tMatchtype: "+matchType)
#print(geocode_result.features[bestMatchRecordNumber])
else: # no point matches
#print("No Matches...Trying with other City Names...")
maxMatchScore = 0
citiesInCEG = ['Greenwood','Westfield','Zionsville','Mooresville','Crows Nest','Meridian Hills','Rocky Ripple','Southport','Speedway','Indianapolis','Clermont','Linton','Avon','Brownsburg','Plainfield','Beech Grove','Fishers','Carmel']
for cityName in citiesInCEG:
#addressWithoutCity = addressString.split(",")[0]+ ", Indiana, USA"
newCityAddress = addressString.split(",")[0]+", "+cityName+ ", Indiana, USA"
#print(newCityAddress)
new_geocode_result = geocode(address=newCityAddress , as_featureset=True)
##
resultNumber = 0
#bestNewMatchRecordNumber=0
for new_geoResult in new_geocode_result.features:
matchScore = 0
match_type = new_geocode_result.features[resultNumber].attributes["Addr_type"]
matchAddress = new_geocode_result.features[resultNumber].attributes['Match_addr']
matchRegion = new_geocode_result.features[resultNumber].attributes['Region']
#print(matchAddress)
if match_type == "PointAddress":# and matchAddress.split(",")[0].strip() == addressWithoutCity.split(",")[0].strip() and matchRegion == "Indiana":
#print(new_geocode_result.features[resultNumber])
matchScore = new_geocode_result.features[resultNumber].attributes["Score"]
#print(matchScore)
if matchScore > maxMatchScore:
maxMatchScore = matchScore
bestNewMatchRecordNumber = resultNumber
if bestMatchRecordNumber!=-1:
#print(new_geocode_result.features[bestNewMatchRecordNumber])
longitude = new_geocode_result.features[bestNewMatchRecordNumber].geometry.x
latitude = new_geocode_result.features[bestNewMatchRecordNumber].geometry.y
bestMatchAddress = new_geocode_result.features[bestNewMatchRecordNumber].attributes['Match_addr']
#print(bestMatchAddress)
matchScore = new_geocode_result.features[bestNewMatchRecordNumber].attributes["Score"]
#print("\t"+str(matchScore)+"% geocode match")
matchType = new_geocode_result.features[bestNewMatchRecordNumber].attributes["Addr_type"]
#print("\tMatchtype: "+matchType)
resultNumber +=1
##street match search
if bestMatchRecordNumber==-1:# or maxMatchScore<93.1:
citiesInCEG = ['Indianapolis','Greenwood','Zionsville','Mooresville','Crows Nest','Meridian Hills','Rocky Ripple','Southport','Speedway','Clermont','Linton','Avon','Brownsburg','Plainfield','Beech Grove','Fishers','Carmel']
resultNumber = 0
maxMatchScore = 0
bestMatchRecordNumber = -1
###########################################
### street name search
###########################################
resultNumber =0
for geoResult in geocode_result.features:
## print("made it here")
## print(resultNumber)
match_type = geocode_result.features[resultNumber].attributes["Addr_type"]
if match_type == "StreetName":
#print(geocode_result.features[resultNumber])
matchScore = geocode_result.features[resultNumber].attributes["Score"]
if matchScore > maxMatchScore:
maxMatchScore = matchScore
bestMatchRecordNumber = resultNumber
longitude = geocode_result.features[bestMatchRecordNumber].geometry.x
latitude = geocode_result.features[bestMatchRecordNumber].geometry.y
matchAddress = geocode_result.features[bestMatchRecordNumber].attributes['Match_addr']
#print(matchAddress)
matchScore = geocode_result.features[bestMatchRecordNumber].attributes["Score"]
#print(str(matchScore)+"% geocde match")
matchType = geocode_result.features[bestMatchRecordNumber].attributes["Addr_type"]
#print("\tMatchtype: "+matchType)
#print(bestMatchRecordNumber)
if bestMatchRecordNumber == -1:
for cityName in citiesInCEG:
#addressWithoutCity = addressString.split(",")[0]+ ", Indiana, USA"
newCityAddress = addressString.split(",")[0]+", "+cityName+ ", Indiana, USA"
#print(newCityAddress)#+" K")
new_geocode_result = geocode(address=newCityAddress , as_featureset=True)
##
newResultNumber = 0
#bestNewMatchRecordNumber=0
for new_geoResult in new_geocode_result.features:
newResultNumber = 0
match_type = new_geocode_result.features[newResultNumber].attributes["Addr_type"]
matchAddress = new_geocode_result.features[newResultNumber].attributes['Match_addr']
matchRegion = new_geocode_result.features[newResultNumber].attributes['Region']
#print(matchAddress)
if match_type == "StreetAddress" or match_type == "StreetName":# and matchAddress.split(",")[0].strip() == addressWithoutCity.split(",")[0].strip() and matchRegion == "Indiana":
#print(new_geocode_result.features[resultNumber])
matchScore = new_geocode_result.features[newResultNumber].attributes["Score"]
#print(matchScore)
if matchScore > maxMatchScore:
maxMatchScore = matchScore
bestNewMatchRecordNumber = newResultNumber
#print(new_geocode_result.features[bestNewMatchRecordNumber])
longitude = new_geocode_result.features[bestNewMatchRecordNumber].geometry.x
latitude = new_geocode_result.features[bestNewMatchRecordNumber].geometry.y
bestMatchAddress = new_geocode_result.features[bestNewMatchRecordNumber].attributes['Match_addr']
#print(bestMatchAddress)
matchScore = new_geocode_result.features[bestNewMatchRecordNumber].attributes["Score"]
#print("\t"+str(matchScore)+"% geocde match")
matchType = new_geocode_result.features[bestNewMatchRecordNumber].attributes["Addr_type"]
#print("\tMatchtype: "+matchType)
#print(latitude,longitude)
newResultNumber +=1
resultNumber +=1
#print(resultNumber)
if maxMatchScore>93:
## try:
latlong = str(latitude)+"+"+str(longitude)
print(bestMatchAddress)
#matchScore = new_geocode_result.features[bestNewMatchRecordNumber].attributes["Score"]
print("\t"+str(matchScore)+"% geocde match")
#matchType = new_geocode_result.features[bestNewMatchRecordNumber].attributes["Addr_type"]
print("\tMatchtype: "+matchType)
print(latitude,longitude)
return latlong
## except:
## latlong = None
else:
latlong = None
FullAddress = "500 S Capitol Ave"
city = "Indianapolois"
address = FullAddress
address = address.replace(" ","+")
url = "https://xmaps.indy.gov/arcgis/rest/services/Locators/IndyStreets/GeocodeServer/findAddressCandidates?Street="+address+"&City="+city+"&ZIP=&Single+Line+Input=&category=&outFields=&maxLocations=&outSR=4326&searchExtent=&location=&distance=&magicKey=&f=json"
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
html = urllib.request.urlopen(url, context=ctx).read()
my_bytes_value = html.decode().replace("'", '"')
jsonResult = json.loads(my_bytes_value)
#print(jsonResult)
my_bytes_value = html.decode().replace("'", '"')
jsonResult = json.loads(my_bytes_value)
#print(jsonResult)
if jsonResult['candidates']:
print("result found")
#print(jsonResult['candidates'][0])
x = jsonResult['candidates'][0]['location']['x']
y = jsonResult['candidates'][0]['location']['y']
score = jsonResult['candidates'][0]['score']
print(jsonResult['candidates'][0]['address'])
#matchScore = new_geocode_result.features[bestNewMatchRecordNumber].attributes["Score"]
print("\t"+str(score)+"% geocde match")
#matchType = new_geocode_result.features[bestNewMatchRecordNumber].attributes["Addr_type"]
#print("\tMatchtype: "+matchType)
print(latitude,longitude)
latitude = x
longitude = y
latlong_dict[WO] = str(latitude)+"+"+str(longitude)
else:
addressString = FullAddress + ", " + city + ", IN"
print(addressString)
latlong = ESRIGeolocator(addressString)
... View more
01-29-2024
10:43 AM
|
1
|
1
|
374
|
POST
|
Would Mapbox work? This is what I include in automated emails to plot points on a Mapbox street basemap in the email body via Python. (replace the TOKEN with your API Mapbox TOKEN) EmailBody += "\n<b>Map of Ticket Location: </b><br>"
EmailBody += r'''<img width="600" src="https://api.mapbox.com/styles/v1/mapbox/streets-v11/static/pin-m-marker+285A98('''+str(x)+''','''+str(y)+'''/'''+str(x)+''','''+str(y)+''',13,0/600x300@2x?access_token=TOKEN">'''
... View more
11-29-2023
12:56 PM
|
0
|
0
|
254
|
POST
|
Make sure your AGOL account you're running the script from is still an AGOL Admin in your org. If not (like before I was made an Admin in my Org) I could only view my own user details via Python but now I can see others lastLogin. I just verified this using a test account in AGOL and I get the following error (which I don't get via my Admin login). AttributeError: 'User' object has no attribute 'lastLogin'
... View more
11-29-2023
12:28 PM
|
0
|
1
|
297
|
POST
|
I’ve been encountering similar issues. I have found that ArcGIS Pro (which we license through AGOL) automatically logs itself out of every 90 days. I have many Arcpy scripts running via Task Scheduler 24/7. Also, periodically (usually once a day at a specific time) scripts will fail saying “RuntimeError: The Product License has not been initialized.” No idea what is causing this error as this script runs all day every 30 mins and never gets this error the rest of the day. ESRI Tech Support sent me this suggestion which we have yet to implement… ------------------------------------------- We’ve done a bit of digging into our documentation and might have a solution for you. The bad news is, it doesn’t look like there’s a good way to handle the Pro license refresh through Python. The good news is, there is a promising option for handling it in your environment directly. Please see below for a configuration step-by-step that should solve your logout issue: Step 1: Environmental settings Convert your Named license to a Single Use license for this instance of Pro (if you haven’t already). See https://pro.arcgis.com/en/pro-app/latest/get-started/convert-named-user-licenses-to-single-use.htm for more details on how to configure this. This should allow offline access for Pro. Make sure “Sign me in automatically” remains checked when you log into Pro on this machine. Just in case. Step 2: Caching local user (src: https://community.esri.com/t5/python-questions/arcpy-fails-to-import-when-not-logged-into-host-machine/td-p/553399) Log into the server that will host the script using the username that will be running the script (i.e. the “owner” in task scheduler). Once logged in, open ArcGIS Pro (this will create an esri profile cookie in your AppData folder, that ArcGIS will be able to use to recognize the user). Make sure your license and configurations are set according to step 1 and close Pro. Step 3: Just in case… (src: https://community.esri.com/t5/arcgis-pro-questions/running-a-scheduled-task-on-a-server-machine/m-p/94134) If the issue persists after running through steps 1 and 2, it means that your Pro configuration requires the application to be open while running scripts against its library, for whatever reason. If this is the case, and only after completing steps 1 and 2, we recommend you include a task before the script in your task scheduler that will open ArcGIS Pro, to remove any weird library locks. This is an edge case but does appear to affect some users, so I wanted to include it in the outline.
... View more
11-24-2021
10:29 AM
|
6
|
4
|
16987
|
POST
|
Hi @Anonymous User – thanks for the quick reply! This is for a street cut restoration workflow which has field crews visit a site on two different occasions… I am using Survey123 for field crews to complete their initial street restoration form including taking a picture of the initial restoration. Another crew will go out later to complete the final restoration and click the existing point (preferably in Field Maps) and fill in the final restoration width, restoration length, restoration notes (optional) and take a final picture. So all points will ultimately have 2 photos (initial and final photo). Trying to edit existing records with Survey123 is not easy but doable. I’d rather the second field crew work exclusively in Field Maps since they can see the points they need to visit in the map. I can hide all the fields except the ones they need to fill out and make those required for them, but I can’t require them to take a picture which we need for our records. I don’t expect any offline editing.
... View more
12-22-2020
11:41 AM
|
3
|
2
|
3141
|
POST
|
Can you require capturing a photo in Field Maps, as you can in Survey123? If not, is this a planned future capability? I’d really like to use Field Maps for a portion of my workflow but I need to require a photo be taken. I'll have to use Survey123 until this capability is added.
... View more
12-22-2020
11:20 AM
|
27
|
24
|
4579
|
POST
|
Christina Miller I was trying to do the exact same thing as you when I found your post. I’m just shocked ESRI doesn’t provide these kinds of reports out of the box. I spent many hours trying to figure out how to read the webmapID in a given app/dashboard with Python (which I could see in AGOL Assistant JSON view). Luckily, I eventually found the solution: See line In [13]: https://developers.arcgis.com/python/guide/cloning-content/ Attached is the script I developed. It searches your ArcGIS Online for any web apps and dashboards and will then list each of those items and its details, the webmap associated to it and its details, and then every layer in that map and it's URL.
... View more
10-08-2020
06:17 AM
|
2
|
0
|
807
|
Title | Kudos | Posted |
---|---|---|
1 | 3 weeks ago | |
1 | a month ago | |
2 | 3 weeks ago | |
1 | 02-28-2024 12:29 PM | |
1 | 01-29-2024 10:43 AM |
Online Status |
Offline
|
Date Last Visited |
21m ago
|