Filter GeoJSONDataSource with CDS view

I have a geojsondatasource with multilines that I am plotting a map. I would like to use a select widget to filter it by country, I have been trying to figure something out, but as it seems I am running out of option and frustration started to kick-in, anyone out there with can let me know if it is possible?
I tried to remove all the unneeded code part to make it as minimal as possible.

dfr = pd.read_csv('routes.csv', index_col=['Source airport ID'], escapechar='\\')
dfr = dfr[(dfr.index != 'N') & (dfr['Airline ID'] != 'N')]

df_r = dfr.copy(deep=True)
df_r = df_r[df_r['Airline ID'].astype(int).isin(dff['Airline ID'].astype(int).to_list())]
df_r.index = df_r.index.astype(int)
df_r.replace('N',0, inplace=True)
df_r['Destination airport ID'] = df_r['Destination airport ID'].astype(int)


di_lat = {k:v for k,v in zip(dff.index, dff['Latitude'])}
di_lon = {k:v for k,v in zip(dff.index, dff['Longitude'])}
di_countries = {k:v for k,v in zip(dff.index, dff['Country'])}


df_r['source_lat'] = df_r.index.map(di_lat)
df_r['source_lon'] = df_r.index.map(di_lon)

df_r['dest_lat'] = df_r['Destination airport ID'].map(di_lat)
df_r['dest_lon'] = df_r['Destination airport ID'].map(di_lon)

df_r['source_airport'] = df_r.index.map(di_aiportN)
df_r['dest_airport'] = df_r['Destination airport ID'].map(di_aiportN)

df_r['source_country'] = df_r.index.map(di_countries)
df_r['dest_country'] = df_r['Destination airport ID'].map(di_countries)



geometry = [LineString([[df_r.iloc[i]['source_lon'], df_r.iloc[i]['source_lat']], [df_r.iloc[i]['dest_lon'], df_r.iloc[i]['dest_lat']]]) for i in range(df_r.shape[0])]
df_rGIS = gpd.GeoDataFrame(df_r, geometry=geometry, crs='EPSG:4326')

df_rGIS.dropna(inplace=True)

world = gpd.read_file('ne_50m_admin_0_countries/ne_50m_admin_0_countries.shp')
world = world[['NAME','SOV_A3','geometry']]
world.replace('Czechia', 'Czech Republic', inplace=True)
world = world[world.NAME != 'Antarctica']

def GIS(geo, geo1):
    GIS = json.loads(geo.reset_index().to_json())
    with open('GIS.json', 'w') as outfile:
        json.dump(GIS, outfile)


    #import JSON files to be plotted
    with open('GIS.json', 'r', encoding='utf8') as openfile: 
            # Reading from json file 
            GIS = GeoJSONDataSource(geojson=openfile.read())
            
    GISr = json.loads(geo1.reset_index().to_json())
    with open('GISr.json', 'w') as outfile:
        json.dump(GISr, outfile)


    #import JSON files to be plotted
    with open('GISr.json', 'r', encoding='utf8') as openfile: 
            # Reading from json file 
            GISr = GeoJSONDataSource(geojson=openfile.read())
                        
        
    pA = figure(x_axis_location = None, y_axis_location = None, width=1200, match_aspect=True,tools = 'pan, wheel_zoom',
               x_axis_type='mercator', y_axis_type='mercator')

    pA.title.align='center'
    pA.patches('xs', 'ys', fill_alpha = 0.7, source = GIS, fill_color = 'Colors', line_width=.2, line_color='white')

    
    pA.circle(x='source_lon', y='source_lat', line_color=None, line_width=.3, color='green', size=3, source=GISr,
              hatch_alpha=1.0, hover_fill_alpha=0.7, hover_fill_color='#FEE715')
    
    pA.circle(x='dest_lon', y='dest_lat', line_color='blue', line_width=.1, color='green', size=3, source=GISr,
          hatch_alpha=1.0, hover_fill_alpha=0.7, hover_fill_color='#FEE715')
    

    pA.patches('xs', 'ys', fill_alpha = 0.7, source = GISr, fill_color = 'Colors', line_width=.2, 
           line_color='lightblue', line_alpha=.4)
    
    pA.grid.grid_line_color=None
    pA.outline_line_color=None
    pA.toolbar.autohide = True
    
    pA.outline_line_color=None
    pA.background_fill_color = 'black'
    pA.border_fill_color = None

    
    show(pA)
    
GIS(world, df_rGIS)

datadata

I’m sorry @Reinhold83 but I don’t really understand your issue. You mention trying to use a CDSview with a select widget, but your (incomplete) example code has neither, and your description does not actually describe any details of how things failed to work (A python error? A JS error? A silent error?)

In order to help offer guidance we need some version of that code that you tried to make work, but could not get to work, i.e. a complete Minimal Reproducible Example. The “complete” part is critical. Often times an experienced used can diagnose problems nearly immediately if they can actually run real code. It is the single most important thing you can do to help others help you.

Thanks for your reply @Bryan, I will post it here soon, busy with other things at moment. Basically it uses one GeoDS for the whole data and a second one with a CDSview to filter based on the select widget.
Anyhow I will update the code asap.

Here is how far I have got, I am getting an error for the source

ValueError: failed to validate CustomJSFilter(id=‘p130898’, …).args: Disallowed keys: {‘source’}

 dfr = pd.read_csv('routes.csv', index_col=['Source airport ID'], escapechar='\\')
 dfr = dfr[(dfr.index != 'N') & (dfr['Airline ID'] != 'N')]
 
 df_r = dfr.copy(deep=True)
 df_r = df_r[df_r['Airline ID'].astype(int).isin(dff['Airline ID'].astype(int).to_list())]
 df_r.index = df_r.index.astype(int)
 df_r.replace('N',0, inplace=True)
 df_r['Destination airport ID'] = df_r['Destination airport ID'].astype(int)
 
 di_lat = {k:v for k,v in zip(dff.index, dff['Latitude'])}
 di_lon = {k:v for k,v in zip(dff.index, dff['Longitude'])}
 di_countries = {k:v for k,v in zip(dff.index, dff['Country'])}
 
 df_r['source_lat'] = df_r.index.map(di_lat)
 df_r['source_lon'] = df_r.index.map(di_lon)
 
 df_r['dest_lat'] = df_r['Destination airport ID'].map(di_lat)
 df_r['dest_lon'] = df_r['Destination airport ID'].map(di_lon)
 
 df_r['source_airport'] = df_r.index.map(di_aiportN)
 df_r['dest_airport'] = df_r['Destination airport ID'].map(di_aiportN)
 
 df_r['source_country'] = df_r.index.map(di_countries)
 df_r['dest_country'] = df_r['Destination airport ID'].map(di_countries)
 
 geometry = [LineString([[df_r.iloc[i]['source_lon'], df_r.iloc[i]['source_lat']], [df_r.iloc[i]['dest_lon'], df_r.iloc[i]['dest_lat']]]) for i in range(df_r.shape[0])]
 df_rGIS = gpd.GeoDataFrame(df_r, geometry=geometry, crs='EPSG:4326')
 
 df_rGIS.dropna(inplace=True)
 
 world = gpd.read_file('ne_50m_admin_0_countries/ne_50m_admin_0_countries.shp')
 world = world[['NAME','SOV_A3','geometry']]
 world.replace('Czechia', 'Czech Republic', inplace=True)
 world = world[world.NAME != 'Antarctica']
 
 
 GIS = json.loads(world.reset_index().to_json())
 with open('GIS.json', 'w') as outfile:
     json.dump(GIS, outfile)
 
 
 with open('GIS.json', 'r', encoding='utf8') as openfile: 
         GIS = GeoJSONDataSource(geojson=openfile.read())
 
 GISr = json.loads(df_rGIS.reset_index().to_json())
 with open('GISr.json', 'w') as outfile:
     json.dump(GISr, outfile)
 
 
 with open('GISr.json', 'r', encoding='utf8') as openfile: 
         GISr = GeoJSONDataSource(geojson=openfile.read())
         
 countries = list(sorted(df_rGIS.source_country.unique()))
 
 
 select = Select(title='Select team A:', align='start', value='United States', options=countries, width=130, margin = (15, 5, 0, 0))
 
 select.js_on_change('value', CustomJS(args=dict(source=GISr), code="""
    source.change.emit() """))
 
 cds_filter = CustomJSFilter(args=dict(source=GISr, select=select, countries=countries), code='''
     var ccountrieslist = [ ];
     for (var i = 0; i < source.get_length(); i++){
         if (source.data['source_country'][i] = select.value){
             ccountrieslist.push(true);
         } else {
             ccountrieslist.push(false);}}
 
     selected = []
     for (i in countrieslist) {
         let sel_countries = countries[i])
         console.log(sel_countries)
         console.log(i, ccountrieslist[i], source.data['source_country'][i], sel_countries.includes(source.data['source_country'][i]))
         if(countrieslist[i] && sel_countries.includes(source.data['source_country'][i])) {
             selected.push(true)
         }
         else {
             selected.push(false)
         }}
     return selected;
 ''')

 view = CDSView(source=GISr, filters=[cds_filter])
 
 
 pA = figure(x_axis_location = None, y_axis_location = None, width=1200, match_aspect=True,tools = 'pan, wheel_zoom',
            x_axis_type='mercator', y_axis_type='mercator')
 
 pA.title.align='center'
 pA.patches('xs', 'ys', fill_alpha = 0.7, source = GIS, fill_color = 'Colors', line_width=.2, line_color='black')
 
 
 pA.circle(x='source_lon', y='source_lat', line_color=None, line_width=.3, color='green', size=2.2, source=GISr,
          hatch_alpha=1.0, hover_fill_alpha=0.7, hover_fill_color='#FEE715', view=view)

 pA.circle(x='dest_lon', y='dest_lat', line_color='blue', line_width=.1, color='green', size=2.2, source=GISr,
       hatch_alpha=1.0, hover_fill_alpha=0.7, hover_fill_color='#FEE715', view=view)
 
 pA.patches('xs', 'ys', fill_alpha = 0.4, source = GISr, line_width=.2, 
            line_color='lightblue', line_alpha=.4, view=view)
 
 pA.grid.grid_line_color=None
 pA.outline_line_color=None
 pA.toolbar.autohide = True
 pA.outline_line_color=None
 pA.border_fill_color = None
 show(column(select,pA))

Hi @Reinhold83 Thanks for the MRE, please edit your post to use code formatting so that the code is intelligible (either with the </> icon on the editing toolbar, or triple backtick ``` fences around the code blocks)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.