Logo di Leaflet

Leaflet

Community
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().

Panoramica

Autoreznlgis
Repositoryopengis-skills
Nome della skillleaflet
Stelle
76
Fork
12
File inclusi
Solo istruzioni
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • Tutto nelle istruzioni

    Tutto ciò che serve al modello è nelle istruzioni: nessun file aggiuntivo da sincronizzare.

  • Open source

    Pubblicata da znlgis su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Leaflet in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/znlgis/opengis-skills/tree/main/gis/leaflet
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Nuova skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella nella cartella delle skill di quell'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
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Leaflet in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Leaflet non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Leaflet non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello 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 不要硬编码进提交的前端代码。

相关技能

参考资源

Domande frequenti

Cosa fa la skill 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().

Perché usare Leaflet su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Leaflet è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Leaflet in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/znlgis/opengis-skills/tree/main/gis/leaflet. TypingMind legge il file SKILL.md e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Leaflet?

Qualsiasi modello che colleghi in TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Leaflet?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Leaflet: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Leaflet è gratuita?

Sì. È pubblicata su GitHub da znlgis con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, modelli o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Vedi tutti

Crea subito la tua area di lavoro IA

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇