Feature layer fromcsv and excel data using makeFeatureLayer and want to add this layer to a newly created webmap .

553
1
09-28-2023 09:14 PM
BhupendarBhandari
New Contributor

I created a feature layer from excel and csv data using makeFeatureLayer method and after creating the feature layer i want to add this feature layer to a newly created webmap object and then host it to AGOL
Is this possible if not suggest other way for this workFlow.

def make_feature_layer_using_csv_excel():
    file_path=input("Enter the file Path: ")
    file_name = os.path.splitext(os.path.basename(file_path))[0]
    wm = WebMap()

    feature_class_file_name=file_name+'_'+'featureClass'
    feature_layer_name=file_name+'_'+'Layer'
    
    
    
    print("fileName: ",file_name)
    output_file_dir=os.path.join(os.getcwd(),"MyProject1.gdb")
    output_file_path=os.path.join(output_file_dir,feature_class_file_name)
    feature_layer_path=os.path.join(os.getcwd(),file_name+'.lyrx')
    print("outputfilePath: ",feature_layer_path)
    
    file_extension=os.path.splitext(file_path)[1].lower()
    
    if file_extension == '.csv':
        arcpy.conversion.TableToTable(file_path, output_file_dir, file_name)
    elif file_extension in ['.xlsx', '.xls', '.xlsb']:
        arcpy.conversion.ExcelToTable(file_path, output_file_dir,file_name)
    else:
        return "Unknown"

    arcpy.management.XYTableToPoint(file_path, output_file_path,"Longitude", "Latitude")
    feature_layer=arcpy.management.MakeFeatureLayer(output_file_path, out_layer='featureLayer')
    
    arcpy.management.SaveToLayerFile('featureLayer',feature_layer_path )
    featureLayer=feature_layer.getOutput(0)
    print(type(featureLayer))
    insertLyr = arcpy.mp.LayerFile(feature_layer_path)
   
    print("feature_layer",featureLayer)
0 Kudos
1 Reply
EarlMedina
Esri Regular Contributor

This is a really simplified example, but you can accomplish this using only the ArcGIS API for Python like so:

 

import pandas as pd
from arcgis.features import GeoAccessor, GeoSeriesAccessor
from arcgis.gis import GIS
from arcgis.mapping import WebMap

gis = GIS("https://machine.domain.com/portal", "admin", "password")
df = pd.read_csv("/path/to/sample.csv") # or pd.read_excel
sedf = pd.DataFrame.spatial.from_xy(df=df, x_column="LONGITUDE", y_column="LATITUDE", sr=4326)
lyr = sedf.spatial.to_featurelayer("csv_featureLayer", gis=gis)
wm = WebMap()
wm.add_layer(lyr)

item_properties = {"title":"CSV test", "snippet": "whatever", "tags": ["automation", "python"]}
wm_item = wm.save(item_properties)

 

0 Kudos