Leaflet logo

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

Overview

Publisherznlgis
Repositoryopengis-skills
Skill nameleaflet
Stars
76
Forks
12
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by znlgis on GitHub. Read the source before you install it.

Installation

Install the Leaflet AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/znlgis/opengis-skills/tree/main/gis/leaflet
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Leaflet in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Leaflet on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Leaflet is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

项目地址: 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 不要硬编码进提交的前端代码。

相关技能

参考资源

Frequently asked questions

What does the Leaflet AI skill do?

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

Why use Leaflet on TypingMind?

Because you install it once and use it with any model. Leaflet is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Leaflet in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/znlgis/opengis-skills/tree/main/gis/leaflet. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Leaflet?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Leaflet?

As many as you like. As long as a model supports skills, you can use Leaflet with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Leaflet AI skill free?

Yes. It is published on GitHub by znlgis under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇