Logotipo de Leaflet

Leaflet

Comunidad
znlgis
leaflet

Use when adding lightweight 2D tile maps to web pages with leaflet 1.9.4 — L.map/L.tileLayer, markers, popups, GeoJSON overlays, layer control, [lat, lng] ordering, or debugging blank maps, broken default marker icons after bundling, and sizing fixed by invalidateSize().

Descripción general

Editorznlgis
Repositorioopengis-skills
Nombre de la habilidadleaflet
Estrellas
76
Forks
12
Archivos incluidos
Solo instrucciones
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando una petición es realmente relevante.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por znlgis en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Leaflet en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/znlgis/opengis-skills/tree/main/gis/leaflet
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → Desde URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/znlgis/opengis-skills.git /tmp/opengis-skills
mkdir -p .claude/skills
cp -r /tmp/opengis-skills/gis/leaflet .claude/skills/leaflet
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Leaflet en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición es relevante, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Leaflet automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Leaflet no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición relevante, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

项目地址: https://github.com/Leaflet/Leaflet

官方文档: https://leafletjs.com/

API 参考: https://leafletjs.com/reference.html

示例: https://leafletjs.com/examples.html

最新版本: 1.9.4(截至 2026-10,npm leaflet)

许可证: BSD-2-Clause

概述

Leaflet 是面向移动端与桌面端的开源 2D 地图库,核心构建体积约 42 KB,提供命令式的类 jQuery API。特性:

  • 瓦片图层:支持 OSM、XYZ、WMS、WMTS、ArcGIS 等栅格底图
  • 矢量叠加:Marker、Popup、Tooltip、Circle、Polygon、Polyline、GeoJSON
  • 图层管理:LayerGroup、FeatureGroup、L.control.layers 切换底图与叠加层
  • 事件系统:Map / Layer / Marker 均继承 Evented,统一 on / off / once
  • 插件生态:绘制、聚合、热力图、矢量瓦片等均有成熟第三方插件
  • 框架无关:可在原生 JS、Vue、React、Svelte 中直接使用

环境准备

方式一:CDN

html
<!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"
        integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
          integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
  <style>
    /* 容器必须显式设置高度,否则地图不可见 */
    #map { height: 400px; }
  </style>
</head>
<body>
  <div id="map"></div>
</body>
</html>

方式二:npm

bash
npm install leaflet
javascript
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

验证

打开页面应看到可拖拽、可缩放的 OSM 底图;控制台执行 L.version 返回 "1.9.4"。

javascript
console.log(L.version); // "1.9.4"

核心 API

L.map

javascript
const map = L.map('map', {
  center: [39.9087, 116.3975], // [纬度, 经度]
  zoom: 12,
  zoomControl: true,
  attributionControl: true
});
选项类型默认值说明
centerLatLng无初始中心点 [lat, lng]
zoomNumber无初始缩放级别
zoomControlBooleantrue是否添加缩放控件
attributionControlBooleantrue是否添加版权控件
minZoom / maxZoomNumber无缩放范围限制

L.tileLayer

javascript
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  subdomains: 'abc',
  attribution: '&copy; OpenStreetMap contributors'
}).addTo(map);

URL 模板占位符:{s} 子域、{z} 层级、{x}/{y} 瓦片坐标、{r} 高清后缀(@2x)。

L.marker

javascript
const marker = L.marker([39.9087, 116.3975], {
  draggable: true,
  title: '天安门'
}).addTo(map);

marker.bindPopup('天安门广场').openPopup();

L.geoJSON

javascript
L.geoJSON(geojsonData, {
  style: (feature) => ({ color: '#ff7800', weight: 2 }),
  pointToLayer: (feature, latlng) => L.circleMarker(latlng, { radius: 6 }),
  onEachFeature: (feature, layer) => {
    layer.bindPopup(feature.properties.name);
  },
  filter: (feature) => feature.properties.show !== false
}).addTo(map);
选项签名用途
style(feature) => Path options面/线样式,可传对象或函数
pointToLayer(feature, latlng) => Layer自定义点渲染(如圆点替代默认图标)
onEachFeature(feature, layer) => void为每个要素绑定弹窗、事件
filter(feature) => Boolean返回 false 的要素不渲染
coordsToLatLng(coords) => LatLng自定义坐标转换

L.layerGroup 与图层控制

javascript
const baseLayers = {
  'OSM': L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png'),
  '高德影像': L.tileLayer('https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}')
};

const points = L.layerGroup([marker]);
const overlays = { '标注点': points };

L.control.layers(baseLayers, overlays).addTo(map);
baseLayers['OSM'].addTo(map); // 默认底图需手动添加

事件系统

Map、Layer、Marker 均继承 Evented,使用 on / off / once / fire。

javascript
map.on('click', (e) => console.log(e.latlng));
map.on('zoomend moveend', () => console.log(map.getZoom()));

marker.on('click', () => console.log('marker clicked'));
marker.on('dragend', () => console.log(marker.getLatLng()));

const handler = (e) => console.log(e);
map.on('mousemove', handler);
map.off('mousemove', handler); // 显式移除,避免内存泄漏

常用 Map 事件:click、dblclick、mousemove、zoomend、moveend、layeradd、layerremove、resize、popupopen。


典型工作流

以「底图 + GeoJSON 点位 + 弹窗 + 图层切换」为例:输入 data/poi.geojson([lng, lat]),输出可缩放、可点选、可切层的单页地图。

  1. 初始化地图:L.map('map', { center, zoom }),容器须有确定高度
  2. 添加底图:L.tileLayer(urlTemplate, { attribution }).addTo(map)
  3. 叠加数据:L.geoJSON(data, { style, pointToLayer, onEachFeature })
  4. 绑定交互:layer.bindPopup() / map.on('click', fn)
  5. 图层管理:L.control.layers(baseLayers, overlays).addTo(map)
  6. 自适应视图:map.fitBounds(layer.getBounds())
  7. 销毁清理:组件卸载时调用 map.remove()
javascript
const map = L.map('map', { center: [39.9042, 116.4074], zoom: 11 });

const osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '&copy; OpenStreetMap contributors'
}).addTo(map);

// GeoJSON 坐标是 [lng, lat],Leaflet 需要 [lat, lng]
fetch('/data/poi.geojson')
  .then((r) => r.json())
  .then((geojson) => {
    const poiLayer = L.geoJSON(geojson, {
      pointToLayer: (feature, latlng) => L.circleMarker(latlng, { radius: 6, color: '#e74c3c' }),
      onEachFeature: (feature, layer) => {
        layer.bindPopup(feature.properties.name);
      }
    }).addTo(map);

    map.fitBounds(poiLayer.getBounds(), { padding: [20, 20] });
    L.control.layers({ OSM: osm }, { POI: poiLayer }).addTo(map);
  });

验收:页面先出现 OSM 底图,数据加载后视野自动收缩到点位范围,点击圆点弹出名称;右上角图层控件可切换 POI 显隐。


插件生态

插件通过 L.xxx 扩展,使用时先引入其 CSS/JS,再调用扩展 API。

插件npm 包名用途
Leaflet.drawleaflet-draw交互式绘制/编辑几何(点、线、面、矩形、圆)
Leaflet.markerclusterleaflet.markercluster大量点标记的聚合与展开动画
Leaflet.heatleaflet.heat基于点数据的热力图图层
javascript
// 绘制控件
import 'leaflet-draw';
import 'leaflet-draw/dist/leaflet.draw.css';

const drawnItems = new L.FeatureGroup().addTo(map);
map.addControl(new L.Control.Draw({ edit: { featureGroup: drawnItems } }));
map.on(L.Draw.Event.CREATED, (e) => drawnItems.addLayer(e.layer));
javascript
// 点聚合
import 'leaflet.markercluster';
import 'leaflet.markercluster/dist/MarkerCluster.css';

const cluster = L.markerClusterGroup();
cluster.addLayer(L.marker([39.9, 116.4]));
map.addLayer(cluster);
javascript
// 热力图
import 'leaflet.heat';

const heat = L.heatLayer([[39.9, 116.4, 0.5], [39.91, 116.41, 0.8]], { radius: 25 });
heat.addTo(map);

与 Vue / React 集成

核心原则:用 ref / state 持有 map 实例,在挂载时创建、卸载时 map.remove(),避免重复初始化和内存泄漏。

Vue 3

vue
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

const mapEl = ref(null);
let map = null;

onMounted(() => {
  map = L.map(mapEl.value).setView([39.9087, 116.3975], 12);
  L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
});

onBeforeUnmount(() => {
  map?.remove();
  map = null;
});
</script>

<template>
  <div ref="mapEl" style="height: 400px"></div>
</template>

React

jsx
import { useEffect, useRef } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

export default function MapView() {
  const containerRef = useRef(null);
  const mapRef = useRef(null);

  useEffect(() => {
    const map = L.map(containerRef.current).setView([39.9087, 116.3975], 12);
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
    mapRef.current = map;
    return () => {
      map.remove();
      mapRef.current = null;
    };
  }, []);

  return <div ref={containerRef} style={{ height: 400 }} />;
}

最佳实践

  1. 容器高度:#map 必须有显式高度(如 height: 400px),否则渲染为 0 高度不可见
  2. 及时销毁:单页应用卸载组件时调用 map.remove(),清除事件与 DOM
  3. 事件解绑:自定义监听器用具名函数并通过 map.off(type, handler) 移除
  4. 大数据量:数千点以上使用 leaflet.markercluster 聚合,避免逐点渲染卡顿
  5. 避免重复初始化:同一容器仅调用一次 L.map(),重复调用需先 remove()
  6. 正确坐标顺序:Leaflet 使用 [纬度, 经度],与 GeoJSON 的 [经度, 纬度] 相反
  7. 版权声明:使用 OSM 等底图时在 attribution 中保留版权信息

常见问题

问题原因与解决
地图区域空白 / 不显示容器缺少高度:为 #map 设置 height(如 400px),或地图初始化后调用 map.invalidateSize()
标记图标 404 / 显示为破图npm + 打包器下 leaflet.css 引用的默认图标路径失效,需手动设置 L.Icon.Default 的 iconUrl/iconRetinaUrl/shadowUrl 或改用 CDN 引入 CSS
地图在弹窗/隐藏容器中显示错乱容器尺寸变化后调用 map.invalidateSize() 重算
L is not definedCDN 脚本未加载或引入顺序错误:先加载 leaflet.js 再执行代码;npm 下确认 import L from 'leaflet'
经纬度颠倒导致点跑到别处参数顺序为 [lat, lng];GeoJSON 坐标是 [lng, lat],必要时用 coordsToLatLng 转换
组件切换后内存持续增长卸载时未调用 map.remove(),或事件监听器未 off 解绑
瓦片加载失败 / 跨域检查瓦片服务 URL 模板与 CORS 头;WMS 需确认服务端允许跨域
与 Vue/React 响应式冲突不要把 L.map 实例放进 reactive/useState(会代理内部对象),用普通变量或 useRef 持有

AI 使用建议

  • 执行环境:npm install、npm run build 在终端中执行;纯静态页面可用 python -m http.server 5173 起服务(python 不存在时用 py -3)。
  • 先探测版本:npm ls leaflet(未装则 npm view leaflet version);本技能按 1.9.4 编写,CDN 的 integrity SRI 哈希只对应 1.9.4,换版本必须同步换哈希。
  • 验证产物:构建后 curl.exe -I http://localhost:5173/assets/<入口>.js 确认 200;联网时还可 curl.exe -I https://unpkg.com/leaflet@1.9.4/dist/leaflet.js 核对 CDN 版本;AI 助手通常看不到浏览器画面,把 URL 和“应看到瓦片与标记”交给用户,环境支持读图时用截图核对。
  • 图标与坐标:npm + 打包器下默认 marker 图标会 404,需显式设置 L.Icon.Default 的 iconUrl/iconRetinaUrl/shadowUrl;坐标一律 [lat, lng],GeoJSON 是 [lng, lat]。
  • 生命周期:SPA 卸载必须 map.remove() 并解绑自定义事件;容器隐藏或尺寸变化后 map.invalidateSize()。
  • 常见症状:地图区域空白多为容器没设高度;L is not defined 是脚本顺序或 CDN 失败;漏引 leaflet.css 会导致控件错位。
  • 安全与权限:装包、起服务、改端口前先征得用户同意;天地图等瓦片服务的 tk 不要硬编码进提交的前端代码。

相关技能

参考资源

Preguntas frecuentes

¿Qué hace la habilidad de IA Leaflet?

Use when adding lightweight 2D tile maps to web pages with leaflet 1.9.4 — L.map/L.tileLayer, markers, popups, GeoJSON overlays, layer control, [lat, lng] ordering, or debugging blank maps, broken default marker icons after bundling, and sizing fixed by invalidateSize().

¿Por qué usar Leaflet en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Leaflet está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Leaflet en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/znlgis/opengis-skills/tree/main/gis/leaflet. TypingMind lee su archivo SKILL.md y la instala como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Leaflet?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Leaflet?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Leaflet con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Leaflet?

Sí. znlgis la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver todos

Crea ya tu propio espacio de trabajo IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇