📌 学习目标
- 掌握添加默认标记的实现方法
- 理解相关API的使用
- 能够独立完成类似功能开发
🎯 核心概念
向地图添加默认标记。
💻 完 整 代 码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add a default marker</title>
<meta property="og:description" content="向地图添加默认标记。" />
<meta property="og:created" content="2006-06-25" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.24.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.24.0/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = new maplibregl.Map({
container: 'map',
style: 'https://demotiles.maplibre.org/style.json',
center: [12.550343, 55.665957],
zoom: 6
});
const marker = new maplibregl.Marker()
.setLngLat([12.550343, 55.665957])
.addTo(map);
</script>
</body>
</html>
🔍 代码解析
1. 初始化地图
使用 new maplibregl.Map() 创建地图实例,配置了丹麦哥本哈根区域作为初始视图。
2. 关键配置项
- new maplibregl.Marker(): 创建默认样式的标记实例
- setLngLat(): 设置标记的地理坐标位置
- addTo(): 将标记添加到地图上
⚙️ 参数说明
| options.element | HTMLElement | 否 | 自定义标记元素 |
| options.draggable | boolean | 否 | 是否可拖动,默认false |
| options.color | string | 否 | 标记颜色,默认蓝色 |
| lngLat | [number, number] | 是 | 标记位置 [经度, 纬度] |
🎨 效果说明

运行代码后,地图显示丹麦哥本哈根区域,在地图中心位置显示一个默认样式的蓝色标记图标。用户可以通过鼠标拖拽移动地图,滚轮缩放,右键旋转视角。
💡 常 见 问 题
Q1: 标记没有显示? A: 检查以下几点:
Q2: 如何自定义标记样式? A: 通过element选项自定义标记元素:
const el = document.createElement('div');
el.className = 'custom-marker';
el.style.background = 'red';
el.style.width = '30px';
el.style.height = '30px';
new maplibregl.Marker({element: el})
.setLngLat([12.550343, 55.665957])
.addTo(map);
Q3: 如何移除标记? A: 使用remove()方法移除标记:
const marker = new maplibregl.Marker()
.setLngLat([12.550343, 55.665957])
.addTo(map);
// 移除标记
marker.remove();
📝 练习任务
🌟 最佳实践
🔗 延伸阅读
-
Map API文档
-
MapLibre GL JS 官方文档
-
[下一课预告]:将继续学习地图图层的基础知识
本文是MapLibre GL JS实践课程系列的一部分,欢迎关注收藏





