MapLibre GL JS第53课:用Web字体样式化标签
📌 学习目标
- 掌握用Web字体样式化标签的实现方法
- 理解相关API的使用
- 能够独立完成类似功能开发
🎯 核心概念
将Web字体应用到样式的文本标签。
💻 完 整 代 码
代码示例
<!DOCTYPEhtml><htmllang="en"><head><title>Style labels with Web fonts</title><metaproperty="og:description"content="Apply Web fonts to your style’s text labels. Unlike signed distance field (SDF) glyph sets, Web fonts are available from a variety of providers, or your can make your own using popular tools. This option is suitable for fonts that are only available through a third-party content delivery network (CDN) for technical or legal reasons, as well as fonts that are incompatible with SDF, such as variable fonts. For compatibility with Android and iOS applications, specify equivalent fonts in the style’s font-faces property."><metaproperty="og:created"content="2025-10-31"/><metacharset='utf-8'><metaname="viewport"content="width=device-width, initial-scale=1"><linkrel='stylesheet'href='https://unpkg.com/maplibre-gl@5.24.0/dist/maplibre-gl.css'><scriptsrc='https://unpkg.com/maplibre-gl@5.24.0/dist/maplibre-gl.js'></script><linkrel="preconnect"href="https://fonts.googleapis.com"><linkrel="preconnect"href="https://fonts.gstatic.com"crossorigin><linkhref="https://fonts.googleapis.com/css2?family=Rampart+One&display=swap"rel="stylesheet"><style>body{margin:0;padding:0;}html, body, #map{height:100%;}</style></head><body><divid="map"></div><script>document.fonts.load("24px 'Rampart One'");constmap=newmaplibregl.Map({container:'map',zoom:9,center:[137.9150899566626,36.25956997955441],style:{"version":8,"sources":{"satellite":{"type":"raster","tiles":["https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2020_3857/default/g/{z}/{y}/{x}.jpg"],"tileSize":256},"places":{"type":"geojson","data":{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Azumino"},"geometry":{"type":"Point","coordinates":[137.9054972,36.3044083]}},{"type":"Feature","properties":{"name":"Matsumoto"},"geometry":{"type":"Point","coordinates":[137.9687141,36.2382047]}}]}}},"layers":[{"id":"satellite","type":"raster","source":"satellite"},{"id":"places","type":"symbol","source":"places","layout":{"text-font":["Rampart One"],"text-size":24,"text-field":["get","name"]},"paint":{"text-color":"white"}}]}});</script></body></html>🔍 代码解析
1. 初始化地图
使用new maplibregl.Map()创建地图实例,配置了卫星影像底图和GeoJSON点数据源。关键点在于通过内联样式对象配置地图,而非使用外部样式URL。
2. 关键配置项
- document.fonts.load(): 预先加载Web字体,确保字体在地图渲染前可用
- text-font: 指定使用的Web字体名称(如
Rampart One) - text-field: 使用表达式
["get", "name"]从GeoJSON属性中获取标签文本 - text-color: 设置标签颜色为白色,与卫星底图形成对比
⚙️ 参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| text-font | array | 是 | 指定字体名称数组,支持回退机制 |
| text-size | number | 是 | 标签字体大小(像素) |
| text-field | expression | 是 | 定义标签显示内容的表达式 |
| text-color | string | 否 | 标签颜色,默认黑色 |
🎨 效果说明
运行代码后,地图显示日本松本市和安曇野市区域的卫星影像底图,在两个标记点上方显示白色的地名标签,字体使用Google Fonts提供的Rampart One字体,呈现独特的手写风格。
💡 常 见 问 题
Q1: Web字体显示为默认字体怎么办?
A:检查以下几点:
- 确认已在HTML中引入字体链接(如Google Fonts的link标签)
- 使用
document.fonts.load()确保字体加载完成后再渲染 - 检查字体名称是否正确,注意大小写敏感
Q2: Web字体在移动端不显示?
A:某些移动浏览器对Web字体支持有限,建议:
- 在style的font-faces属性中指定fallback字体
- 考虑使用系统字体作为备选
- 使用font-display: swap提高加载体验
Q3: 如何确保字体加载性能?
A:使用document.fonts.readyPromise等待字体加载完成:
document.fonts.ready.then(()=>{// 字体已加载,初始化地图});📝 练习任务
- 基础练习:尝试更换为其他Google Fonts字体(如Roboto、Open Sans)
- 进阶挑战:添加多个不同字体的标签层,展示字体效果差异
- 拓展思考:如何实现根据缩放级别动态切换字体大小?
- 综合实践:创建一个支持中英文双语标签的地图,使用不同字体
🌟 最佳实践
- 字体预加载: 使用
document.fonts.load()或font-display: swap避免FOIT(Flash of Invisible Text) - 字体回退: 在text-font数组中按优先级排列多个字体,确保兼容性
- 跨平台兼容: 为Android和iOS应用在style的font-faces中指定等效字体
- 性能优化: 只加载必要的字重和字符集,减少字体文件大小
- 对比度保证: 标签颜色与底图要有足够对比度,确保可读性
🔗 延伸阅读
Map API文档
MapLibre GL JS 官方文档
[下一课预告]:将继续学习地图图层的基础知识
