You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何消除Streamlit中leafmap地图边距?NetCDF图层选folium还是leafmap?

问题与解决方案

问题描述

  • 希望leafmap地图完全占据Streamlit主区域,无任何边距,但目前存在上下边距,增大height参数会产生Y轴偏移,需适配静态窗口。
  • 需要添加NetCDF格式图层,询问选择folium还是leafmap更合适。

用户当前代码:

import streamlit as st
import leafmap.foliumap as leafmap 

st.set_page_config(
    page_title=None,
    page_icon=None,
    layout="wide",
    initial_sidebar_state="auto",
)
st.markdown(
    """
    <style>
        header {visibility: hidden;}
        footer {visibility: hidden;}
        .block-container {
            padding: 0 !important;
            margin: 0 !important;
            max-width: 100% !important;
            width: 100% !important;
        }
        .main {
            padding: 0 !important;
            margin: 0 !important;
        }
        .css-1aumxhk {
            margin-top: 0 !important;
        }
    </style>
    """,
    unsafe_allow_html=True,
)

m = leafmap.Map(center=[-0.1807, -78.4678], zoom=7)
m.to_streamlit(height=830)

一、解决leafmap全屏无间距问题

你的自定义CSS未覆盖所有默认间距,且固定height值会导致适配问题,调整方案如下:

修改后的完整代码:

import streamlit as st
import leafmap.foliumap as leafmap 

st.set_page_config(
    page_title=None,
    page_icon=None,
    layout="wide",
    initial_sidebar_state="collapsed",  # 可选:不需要侧边栏时折叠
)
st.markdown(
    """
    <style>
        header, footer {visibility: hidden;}
        .block-container {
            padding: 0 !important;
            margin: 0 !important;
            max-width: 100vw !important;
            width: 100vw !important;
        }
        .main {
            padding: 0 !important;
            margin: 0 !important;
        }
        .st-emotion-cache-12fmjuu {  # 适配新版Streamlit主容器间距
            padding-top: 0 !important;
            padding-bottom: 0 !important;
        }
        .folium-map {  # 强制地图占满视口
            position: absolute !important;
            top: 0;
            left: 0;
            width: 100vw !important;
            height: 100vh !important;
        }
    </style>
    """,
    unsafe_allow_html=True,
)

m = leafmap.Map(center=[-0.1807, -78.4678], zoom=7, attr="")
m.to_streamlit()  # 移除固定height,由CSS控制全屏

关键说明:

  • 使用position: absolute结合100vw/100vh强制地图占满整个视口,避免固定高度导致的偏移问题。
  • 适配新版Streamlit的CSS类(.st-emotion-cache-12fmjuu),若你的Streamlit版本不同,可通过浏览器开发者工具查看对应间距类名替换。
  • 折叠侧边栏(可选)可进一步消除额外空间占用。

二、NetCDF图层选择:优先用leafmap

  • leafmap是folium的封装,专为地理数据可视化优化,直接支持NetCDF图层的加载与渲染,无需手动处理复杂的数据转换逻辑。
  • leafmap提供add_netcdf()方法,仅需传入文件路径、变量名等参数即可快速生成图层,还支持时间序列播放、颜色映射调整等实用功能。

示例:在上述地图中添加NetCDF图层

# 替换为你的NetCDF文件路径和变量名
m.add_netcdf(
    "your_dataset.nc",
    var="temperature",
    cmap="viridis",
    layer_name="Temperature Layer"
)

若使用folium,需手动完成NetCDF数据切片、格式转换(如转为GeoJSON或TileLayer),开发成本远高于leafmap,因此优先选择leafmap。


内容的提问来源于stack exchange,提问作者Miguel Angel Gonzalez Cueva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 08:28:16