请求提供用Python Folium制作带可拖拽图例与点击缩放功能的交互地图最小脚本
Folium 交互式地图入门示例
功能实现
- 在地图上显示指定地点的图标标记
- 图例支持鼠标拖拽调整位置
- 点击图例条目自动缩放到对应地点
完整代码
import folium # 定义地点数据:名称、坐标、Font Awesome图标类型 locations = [ {"name": "纽约", "lat": 40.7128, "lon": -74.0060, "icon": "statue-of-liberty"}, {"name": "波士顿", "lat": 42.3601, "lon": -71.0589, "icon": "university"} ] # 创建地图实例,中心设为两地中间位置,初始缩放级别7 m = folium.Map(location=[41.5, -72.5], zoom_start=7) # 为每个地点添加标记,并设置唯一ID用于JS定位 for idx, loc in enumerate(locations): marker_id = f"marker-{idx}" folium.Marker( location=[loc["lat"], loc["lon"]], popup=loc["name"], icon=folium.Icon(icon=loc["icon"], prefix="fa"), # 使用Font Awesome图标 id=marker_id ).add_to(m) # 自定义可拖拽图例的HTML与JS逻辑 legend_template = """ <div id="custom-legend" style="position: fixed; top: 10px; right: 10px; background: white; padding: 10px; border: 1px solid #ccc; border-radius: 5px; cursor: move; z-index: 1000;"> <h4>地点图例</h4> <ul style="list-style-type: none; padding-left: 0;"> {legend_items} </ul> </div> <script> // 实现图例拖拽功能 const legend = document.getElementById('custom-legend'); let isDragging = false; let startX, startY, initialX, initialY; legend.addEventListener('mousedown', (e) => {{ isDragging = true; startX = e.clientX; startY = e.clientY; initialX = legend.offsetLeft; initialY = legend.offsetTop; legend.style.cursor = 'grabbing'; }}); document.addEventListener('mousemove', (e) => {{ if (!isDragging) return; const dx = e.clientX - startX; const dy = e.clientY - startY; legend.style.left = `${{initialX + dx}}px`; legend.style.top = `${{initialY + dy}}px`; legend.style.right = 'auto'; legend.style.bottom = 'auto'; }}); document.addEventListener('mouseup', () => {{ isDragging = false; legend.style.cursor = 'move'; }}); // 点击图例条目缩放至对应地点 document.querySelectorAll('.legend-item').forEach(item => {{ item.addEventListener('click', () => {{ const idx = item.dataset.index; const marker = document.getElementById(`marker-${{idx}}`); if (marker) {{ const lat = parseFloat(marker.getAttribute('data-lat')); const lon = parseFloat(marker.getAttribute('data-lng')); map.setView([lat, lon], 12); // 缩放级别设为12 }} }}); }}); </script> """ # 生成图例条目HTML legend_items_html = "" for idx, loc in enumerate(locations): legend_items_html += f""" <li class="legend-item" data-index="{idx}" style="margin: 5px 0; cursor: pointer;"> <i class="fa fa-{loc['icon']}"></i> {loc['name']} </li> """ # 将图例添加到地图 m.get_root().html.add_child(folium.Element(legend_template.format(legend_items=legend_items_html))) # 保存地图为HTML文件 m.save("interactive_map.html")
使用说明
- 先安装folium:
pip install folium - 运行脚本后,打开生成的
interactive_map.html文件 - 操作方式:
- 拖拽图例的任意位置可调整其在地图上的位置
- 点击图例中的城市名称或图标,地图会自动缩放至对应地点
内容的提问来源于stack exchange,提问作者Sam Sam
相关产品推荐
相关产品推荐

