Stage new mapviewer app: all-field filters, 50-500 garden range, View column with hybrid map modal
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260import osimport jsonimport tempfile
import gradio as uiimport geopandas as gpdimport pandas as pdfrom huggingface_hub import hf_hub_download
DATA_REPO = 'elikoy/mapviewer-data'HF_TOKEN = os.environ.get('HF_TOKEN')
print('Loading Maastricht parcel snapshot ...')PARCELS = gpd.read_parquet( hf_hub_download(DATA_REPO, 'parcels.parquet', repo_type='dataset', token=HF_TOKEN)).to_crs(28992)BUILDINGS = gpd.read_parquet( hf_hub_download(DATA_REPO, 'buildings.parquet', repo_type='dataset', token=HF_TOKEN)).to_crs(28992)print('parcels', PARCELS.shape, '| buildings', BUILDINGS.shape)
ID_COL = 'identificatieLokaalID'DATA = pd.DataFrame(PARCELS.drop(columns='geometry'))
TABLE_COLS = [ ID_COL, 'kadastraleGemeenteWaarde', 'sectie', 'perceelnummer', 'total_parcel_area', 'total_building_footprint', 'calculated_garden_area', 'building_coverage_pct', 'n_buildings', 'bouwjaar_min', 'bouwjaar_max', 'gebruiksdoel', 'has_woonfunctie',]
RENAME = { ID_COL: 'Kadaster_ID', 'kadastraleGemeenteWaarde': 'Gemeente', 'sectie': 'Sectie', 'perceelnummer': 'Perceel', 'total_parcel_area': 'Parcel_m2', 'total_building_footprint': 'Building_m2', 'calculated_garden_area': 'Garden_m2', 'building_coverage_pct': 'Coverage_pct', 'n_buildings': 'N_buildings', 'bouwjaar_min': 'Year_min', 'bouwjaar_max': 'Year_max', 'gebruiksdoel': 'Gebruiksdoel', 'has_woonfunctie': 'Residential',}
DATATYPES = ['str', 'str', 'str', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'str', 'bool', 'html']
NUM_ROUND = ['Parcel_m2', 'Building_m2', 'Garden_m2', 'Coverage_pct']
VIEW_CELL = '<span style="color:#2563eb;text-decoration:underline;cursor:pointer;white-space:nowrap">🗺️ View</span>'
GEMEENTEN = sorted(DATA['kadastraleGemeenteWaarde'].dropna().unique().tolist())SECTIES = sorted(DATA['sectie'].dropna().unique().tolist())DOELEN = sorted(DATA['gebruiksdoel'].dropna().unique().tolist())PARCEL_MAX = float(int(DATA['total_parcel_area'].max()) + 1)
MAP_TEMPLATE = """<!DOCTYPE html><html><head><meta charset='utf-8'/><meta name='viewport' content='width=device-width, initial-scale=1'/><link rel='stylesheet' href='https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'/><script src='https://unpkg.com/leaflet@1.9.4/dist/leaflet.js'></script><style>html, body, #map { height: 100%; margin: 0; padding: 0; }#legend { position: absolute; bottom: 24px; left: 10px; z-index: 800; background: rgba(255,255,255,.93); padding: 8px 10px; font: 12px/1.5 system-ui, sans-serif; border-radius: 6px; box-shadow: 0 1px 5px rgba(0,0,0,.4); }.sw { display: inline-block; width: 12px; height: 12px; margin-right: 6px; vertical-align: -2px; border-radius: 2px; }</style></head><body><div id='map'></div><div id='legend'><div><span class='sw' style='background:#ff6a00'></span>Perceel</div><div><span class='sw' style='background:#3b82f6'></span>BAG gebouwen</div></div><script>var parcel = __PARCEL__;var buildings = __BUILDINGS__;var popupHtml = __POPUP__;var map = L.map('map', { zoomControl: true });var aerial = L.tileLayer('https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg', { maxZoom: 18, maxNativeZoom: 18, attribution: '© PDOK / Beeldmateriaal' });var osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '© OpenStreetMap' });aerial.addTo(map);var parcelLayer = L.geoJSON(parcel, { style: { color: '#ff6a00', weight: 3, fillColor: '#ff6a00', fillOpacity: 0.12 } }).addTo(map);parcelLayer.bindPopup(popupHtml);var bLayer = L.geoJSON(buildings, { style: { color: '#1d4ed8', weight: 1, fillColor: '#3b82f6', fillOpacity: 0.45 } });bLayer.addTo(map);L.control.layers({ 'Luchtfoto (PDOK)': aerial, 'Straatkaart (OSM)': osm }, { 'BAG gebouwen': bLayer, 'Perceel': parcelLayer }, { collapsed: false }).addTo(map);try { map.fitBounds(parcelLayer.getBounds().pad(0.25)); } catch (e) { map.setView([50.8514, 5.6910], 16); }</script></body></html>"""
CSS = """#parcel-modal { position: fixed !important; z-index: 9999; left: 50%; top: 50%; transform: translate(-50%, -50%); width: min(940px, 94vw) !important; max-height: 92vh; overflow: auto; background: #ffffff; border-radius: 14px; padding: 16px; box-shadow: 0 18px 50px rgba(0,0,0,.55); border: 1px solid #e5e7eb; }#results-table { max-height: 620px; }.modal-hint { font-size: 12px; color: #6b7280; }"""
def build_map(pid): sel = PARCELS[PARCELS[ID_COL] == pid] if sel.empty: return '<p>Parcel not found in the snapshot.</p>', 'Parcel not found' row = sel.iloc[0] geom = sel.geometry.iloc[0] parcel_geo = json.loads(sel.to_crs(4326).geometry.to_json())['features'][0]['geometry'] try: near = BUILDINGS.iloc[list(BUILDINGS.sindex.query(geom, predicate='intersects'))] except Exception: near = BUILDINGS[BUILDINGS.intersects(geom)] if len(near): bjson = json.loads(near.to_crs(4326).geometry.to_json()) else: bjson = {'type': 'FeatureCollection', 'features': []} popup = ( '<b>Perceel ' + str(row.get('sectie', '')) + '-' + str(row.get('perceelnummer', '')) + '</b><br/>' + 'Kadaster ID: ' + str(row[ID_COL]) + '<br/>' + 'Gemeente: ' + str(row.get('kadastraleGemeenteWaarde', '')) + '<br/>' + 'Perceel: ' + str(round(float(row.get('total_parcel_area', 0.0)), 1)) + ' m\u00b2<br/>' + 'Bebouwing: ' + str(round(float(row.get('total_building_footprint', 0.0)), 1)) + ' m\u00b2 (' + str(int(row.get('n_buildings', 0))) + ' panden)<br/>' + 'Tuin: <b>' + str(round(float(row.get('calculated_garden_area', 0.0)), 1)) + ' m\u00b2</b>' ) inner = (MAP_TEMPLATE .replace('__PARCEL__', json.dumps(parcel_geo)) .replace('__BUILDINGS__', json.dumps(bjson)) .replace('__POPUP__', json.dumps(popup))) srcdoc = inner.replace('&', '&').replace('"', '"') iframe = ('<iframe style="width:100%;height:540px;border:0;border-radius:10px" ' 'sandbox="allow-scripts allow-same-origin" srcdoc="' + srcdoc + '"></iframe>') title = ('Perceel ' + str(row.get('sectie', '')) + '-' + str(row.get('perceelnummer', '')) + ' \u00b7 ' + str(row.get('kadastraleGemeenteWaarde', '')) + ' \u00b7 ' + str(int(row.get('n_buildings', 0))) + ' pand(en)') return iframe, title
def apply_filters(garden_rng, parcel_lo, parcel_hi, cov_rng, nb_rng, gemeenten, secties, perc_lo, perc_hi, year_rng, excl_year, doelen, residential, idq, limit): df = DATA if parcel_lo is None: parcel_lo = 0.0 if parcel_hi is None: parcel_hi = PARCEL_MAX m = df['calculated_garden_area'].between(garden_rng[0], garden_rng[1]) m = m & df['total_parcel_area'].between(parcel_lo, parcel_hi) m = m & df['building_coverage_pct'].between(cov_rng[0], cov_rng[1]) m = m & df['n_buildings'].between(nb_rng[0], nb_rng[1]) if gemeenten: m = m & df['kadastraleGemeenteWaarde'].isin(gemeenten) if secties: m = m & df['sectie'].isin(secties) if doelen: m = m & df['gebruiksdoel'].isin(doelen) if perc_lo is not None or perc_hi is not None: lo = -1 if perc_lo is None else perc_lo hi = 10 ** 9 if perc_hi is None else perc_hi m = m & df['perceelnummer'].between(lo, hi) if year_rng is not None: y = df['bouwjaar_median'] ym = y.between(year_rng[0], year_rng[1]) if not excl_year: ym = ym | y.isna() m = m & ym if residential == 'Yes': m = m & df['has_woonfunctie'] elif residential == 'No': m = m & (~df['has_woonfunctie']) if idq: m = m & df[ID_COL].astype(str).str.contains(idq.strip(), case=False, na=False) res = df[m] if res.empty: return 'No parcels match these filters. Try widening the ranges.', None, None res = res.sort_values('calculated_garden_area', ascending=False) shown = res[TABLE_COLS].head(int(limit)).copy() shown['View'] = VIEW_CELL shown = shown.rename(columns=RENAME) export = res[TABLE_COLS].rename(columns=RENAME) for frame in (shown, export): for c in NUM_ROUND: frame[c] = frame[c].round(1) csv_path = os.path.join(tempfile.gettempdir(), 'maastricht_parcels_filtered.csv') export.to_csv(csv_path, index=False) status = ('**' + format(len(res), ',d') + '** parcels match (of ' + format(len(df), ',d') + ' in the snapshot). Garden ' + str(garden_rng[0]) + '\u2013' + str(garden_rng[1]) + ' m\u00b2, sorted by garden size; showing top ' + str(len(shown)) + '.') return status, shown, csv_path
def open_modal(table_df, evt: ui.SelectData): try: idx = evt.index[0] if isinstance(evt.index, (list, tuple)) else int(evt.index) pid = str(table_df.iloc[idx, 0]) iframe, title = build_map(pid) return ui.update(visible=True), '### ' + title, iframe except Exception as exc: return ui.update(visible=True), '### Could not load map', '<p>' + str(exc) + '</p>'
with ui.Blocks(title='Maastricht Kadaster Garden Finder', css=CSS) as demo: ui.Markdown('# \U0001f3e1 Maastricht Property & Garden Explorer') ui.Markdown( 'Cadastral parcels (**Kadaster BRK**) joined to building footprints (**BAG**) for the ' 'whole municipality of Maastricht, pre-loaded from a one-time PDOK snapshot.\n\n' '*Garden area = parcel area \u2212 building footprint (intersection-clipped).*' )
with ui.Row(): with ui.Column(scale=1): ui.Markdown('### Filters') garden = ui.Slider(minimum=0, maximum=2000, value=(50, 500), step=10, label='Garden area (m\u00b2)') parcel_lo = ui.Number(value=0, label='Parcel area min (m\u00b2)') parcel_hi = ui.Number(value=PARCEL_MAX, label='Parcel area max (m\u00b2)') cov = ui.Slider(minimum=0, maximum=100, value=(0, 100), step=1, label='Building coverage (%)') nb = ui.Slider(minimum=0, maximum=50, value=(0, 50), step=1, label='Number of buildings') gemeenten = ui.Dropdown(choices=GEMEENTEN, multiselect=True, label='Kadastrale gemeente') secties = ui.Dropdown(choices=SECTIES, multiselect=True, label='Sectie') with ui.Row(): perc_lo = ui.Number(value=None, label='Perceel nr min') perc_hi = ui.Number(value=None, label='Perceel nr max') year = ui.Slider(minimum=1200, maximum=2026, value=(1200, 2026), step=1, label='Bouwjaar (median)') excl_year = ui.Checkbox(value=False, label='Exclude parcels without a known bouwjaar') doelen = ui.Dropdown(choices=DOELEN, multiselect=True, label='Gebruiksdoel') residential = ui.Radio(choices=['Any', 'Yes', 'No'], value='Any', label='Residential (woonfunctie)') idq = ui.Textbox(label='Kadaster ID contains', placeholder='e.g. 3430000927') limit = ui.Slider(minimum=5, maximum=500, value=25, step=5, label='Rows shown') btn = ui.Button('Apply filters', variant='primary') ui.Markdown('<div class="modal-hint">Click any row (or its View cell) to open the ' 'parcel map.</div>')
with ui.Column(scale=3): status = ui.Markdown() table = ui.Dataframe(datatype=DATATYPES, interactive=True, wrap=False, elem_id='results-table', label='Matching parcels') download = ui.File(label='\U0001f4e5 Download filtered CSV')
with ui.Group(visible=False, elem_id='parcel-modal') as modal: modal_title = ui.Markdown() modal_map = ui.HTML() close_btn = ui.Button('\u2715 Close map', elem_id='parcel-modal-close')
inputs = [garden, parcel_lo, parcel_hi, cov, nb, gemeenten, secties, perc_lo, perc_hi, year, excl_year, doelen, residential, idq, limit] btn.click(fn=apply_filters, inputs=inputs, outputs=[status, table, download]) demo.load(fn=apply_filters, inputs=inputs, outputs=[status, table, download]) table.select(fn=open_modal, inputs=[table], outputs=[modal, modal_title, modal_map]) close_btn.click(fn=lambda: ui.update(visible=False), inputs=None, outputs=modal)
if __name__ == '__main__': demo.launch()_space/app.pyAdded+260