How to create a feature layer view in AGOL

2674
20
Jump to solution
04-12-2017 11:14 PM
PaulHaakma
Regular Contributor

Does anyone know how you would, using the Python API, create a feature layer view in ArcGIS Online (or Portal 10.5 for that matter I guess)?

I'm referring here to the new views capability that arrived in AGOL back in December, that allows you to create a view of an existing hosted feature layer, but with different editing capabilities, field visibility, filtered features etc.

Cheers,

-Paul

20 Replies
XabierVelasco_Echeverría
Occasional Contributor

Hi Mitch,

This sample works fine:

gis = GIS("https://www.arcgis.com",usuario,contraseña)
servicio = gis.content.get(idProduccion) ## idProduccion is the itemid of the hosted feature service
flc = arcgis.features.FeatureLayerCollection.fromitem(servicio)
# Delete view if it exists
items = gis.content.search(nombreVista)
if items:
    vistaExistente = gis.content.get(items[0].itemid)    ## this is how you can get the itemid of a hosted feature service
    vistaExistente.delete()
# Crear vista   
vista = flc.manager.create_view(name=nombreVista, spatial_reference=None, extent=None, allow_schema_changes=True, updateable=True, capabilities='Query, Update', view_layers= [flc.layers[1],flc.layers[3]])  ## 1 and 3 are the layers in the hosted feature service that you want to include in the view, you define a list with all the layers you want in

 

Xabier

0 Kudos
MitchEast
New Contributor III

Thanks Xabier,

Unfortunately, that sample does not work for me. I get the error below. What modules are importing?

NameError: name 'arcgis' is not defined

0 Kudos
XabierVelasco_Echeverría
Occasional Contributor

Hi,

You should import the arcgis module (ArcGIS Python API):

import arcgis
from
arcgis.gis import GIS

Regards,

Xabier

jonathanharte
New Contributor III

Thanks Greg, worked a treat .... (eventually!)

Paulg

0 Kudos
GregStevenson
New Contributor III

A sample of mine that I looked up.

view = layer_name.manager.create_view(                                     
                            name='View_name',
                            allow_schema_changes=False,
                            updateable=True,
                            capabilities='Query,Create',
                            view_layers=None)
0 Kudos
XabierVelasco_Echeverría
Occasional Contributor

Hi,

I am able to create the view and update the definition for the feature view and the layers within. Everything works fine, except when I try to update the "fields" parameter in the layer's definition ('fields': listaCampos in the code below). Any ideas about this issue?

from arcgis.gis import GIS
gis = GIS("https://www.arcgis.com",usuario,contraseña)
servicio = gis.content.get(idProduccion)
flc = FeatureLayerCollection.fromitem(servicio)
vista = flc.manager.create_view(name='PRUEBAS6', spatial_reference=None, extent=None, allow_schema_changes=True, updateable=True, capabilities='Query,Update', view_layers=[flc.layers[1],flc.layers[3]])

vflc = FeatureLayerCollection.fromitem(gis.content.get(vista.itemid))
update_dict = {'maxRecordCount': 20000, 'allowGeometryUpdates':False} ## Se señalan 20.000 puesto que es el límite máximo de establecimientos consultables, que es la capa que más elementos puede tener (parcelas y naves solo se consideran las disponibles para el límite, etc.)
vflc.manager.update_definition(update_dict)


vflcAAE = vflc.layers[0]

listaCampos = vflcAAE.properties("fields")
for campo in listaCampos:
    if campo["name"] not in ['Promotor','Agua', 'Electricidad', 'Gas', 'Internet', 'Asociacionismo', 'PlanesPropuestas', 'IncidenciaPavimento', 'IncidenciaSaneamiento', 'IncidenciaElectricidad', 'IncidenciaTelecomunicaciones', 'IncidenciaGasNatural', 'IncidenciaLegal', 'IncidenciaAccesos', 'IncidenciaAlumbrado', 'IncidenciaCallejero', 'IncidenciaLicenciaActividad', 'Estado', 'DireccionUnidad', 'TelefonoUnidad', 'CorreoUnidad', 'AguaInfraestructuras', 'InternetInfraestructuras', 'GestionResiduos', 'EnergiaInfraestructuras', 'Aparcamiento', 'ServiciosComunesUnidad', 'ExcepcionQC', 'QC', 'ObsIncAlumbrado', 'ObsIncCallejero', 'ObsIncLicenciaActividad', 'ObsIncPavimento', 'ObsIncSaneamiento', 'ObsIncElectricidad', 'ObsIncTelecomunicaciones', 'ObsIncGasNatural', 'ObsIncLegal', 'ObsIncAccesos']:
       campo["editable"] = False
    campo["visible"] = True

update_dict = {'maxRecordCount': 2000, "viewDefinitionQuery" : "(cod_mun = '232') OR (cod_mun = '106') OR (cod_mun = '177') OR (last_edited_user = 'industriaEDER')", 'fields': listaCampos}
vflcAAE.manager.update_definition(update_dict)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Thanks,

Xabier

0 Kudos
XabierVelasco_Echeverría
Occasional Contributor

By the way, the error is:

TypeError: Object of type 'PropertyMap' is not JSON serializable

0 Kudos
GregStevenson
New Contributor III

Check that your output is a valid JSON and that listaCampos is in the format you're expecting.

0 Kudos
ThomasPaschke1
Esri Contributor

Hey Xabier,

this snippet is working for me:

viewFL = FeatureLayer.fromitem(view)
fieldList = "POINT_X","POINT_Y","SiteID","Sector"
current_fields = viewFL.properties.fields
new_fields = []
for element in current_fields:
if element["alias"] not in fieldList:
new_fields.append({"name":element["name"],"visible":True})
else:
new_fields.append({"name":element["name"],"visible":False})
update_definition = {"fields": new_fields}
viewFL.manager.update_definition(update_definition)‍‍‍‍‍‍‍‍‍‍

Hope that helps.

Cheers,

Thomas

XabierVelasco_Echeverría
Occasional Contributor

Hi Thomas,

I have used your snippet to update the definition of the "fields" parameter. Now I do not get the error mentioned in my previous post, but when I look to the results, the "fields" parameter has not been updated. Surprisingly, other parameters in the same update are properly performed. i.e. 'maxRecordCount': or "viewDefinitionQuery". Any further ideas? I have noticed that if you change the popup configuration in the Visualization tab of the View in AGOL, it does not update "fields" either, although it seems to behave allright. It is quite wierd

Thanks,

Xabier

NOTE: I have found out that the configuration of the popup is not stored in the view definition, but in the item that references the view. I will try to manipulate the view's popup configuration from Item rather than FeatureLayer. Something similar to what is showed in this link for webmaps:

https://community.esri.com/thread/211499-configure-popup-attributes-programmatically-with-arcgis-api...

0 Kudos