Publish and update web map on ArcGIS Online Using ArcGIS API for Python
Before delving into this story, I highly recommend reading the tutorial authored by my colleague, Yalin Yang, on collecting and updating police incident data from the API provided by the City of Dallas.
Once you’ve done that, you can proceed with the walkthrough on updating files in the ArcGIS Online Dashboard using the ArcGIS Python API.
Please import the Python libraries.
import os
import arcpy
import pandas as pd
from arcgis.gis import GIS,User
from arcgis.mapping import WebMap
from IPython.display import display
from datetime import datetime, timedelta
from arcgis.features import FeatureLayerCollection
Connect to ArcGIS Online.
Publish a feature service from a shapefile
To make a shapefile accessible, begin by uploading the zipped shapefile to the Portal as an item. Then, utilize the publish() method on the item to generate a web layer.
shapefile_path = os.path.join('./update_Data/shapefile/tracts_28days.zip')
added_item = my_gis.content.add({}, data = shapefile_path,folder='Dallas Police Incidents')
published_item = added_item.publish()
Next, you can use the same function to add other layers.
Updating features in a feature layer
As content publishers, you might need to maintain the accuracy of certain web layers over time. With the arrival of new data, tasks such as updating existing ones may become necessary.
Overwriting feature layers
1. Use search() to identify the existing feature that needs to be updated
2. Use fromitem() method returns the layer at the specified index
3. Overwrite the feature layer using the new file we just created
updated_tracts_path = '.\\update_Data\\shapefile\\tracts_28days.zip'
search_results = my_gis.content.search(query="title:tracts_28days", item_type = 'Feature Layer')[0]
incts_collection = FeatureLayerCollection.fromitem(search_results)
incts_collection.manager.overwrite(updated_tracts_path)