Maplibre未请求Glyphs且maplibre-gl-measures插件测量值不显示
问题描述
我基于Angular搭建了演示项目,创建了页面及用于maplibre-gl-js的map-layout组件,随后安装了maplibre-gl-measures插件。代码如下:
import MeasuresControl from 'maplibre-gl-measures' @Component({ selector: "app-map-layout", templateUrl: "./map-layout.component.html", standalone: true, styleUrls: ["./map-layout.component.css"] }) export class MapLayoutComponent implements OnInit{ ngOnInit(): void { const map: maplibregl.Map = new maplibregl.Map({ container: 'map', // container id style: { version: 8, sources: { osm: { type: "raster", tiles: ["https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"], tileSize: 256, attribution: "© OpenStreetMap Contributors", maxzoom: 19 } }, glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf", layers: [ { id: "osm", type: "raster", source: "osm" } ] }, center: [-8, 40], // starting position [lng, lat] zoom: 15 // starting zoom }); console.log('map', map) map.addControl(new MeasuresControl(), "top-left"); } }
添加插件控件后,它仅部分生效:可见按钮,可绘制线条或多边形,但无法显示总长度或面积(示例图:
)。经排查发现Maplibre未向指定地址发送Glyphs请求。我尝试使用本地Glyphs也无效,但官方示例可正常运行,请问我哪里操作有误?
解决办法
等待地图样式加载完成再添加控件
Maplibre地图初始化是异步过程,直接在ngOnInit中添加控件时样式可能未加载完成,导致插件无法绑定Glyphs资源。修改代码,在load事件触发后添加控件:map.on('load', () => { map.addControl(new MeasuresControl(), "top-left"); });触发Glyphs加载逻辑
你的地图只有栅格图层,Maplibre会认为不需要加载Glyphs(Glyphs主要服务于矢量图层的文本渲染),但测量插件需要它来绘制长度/面积文本。可以在样式中添加一个不会显示内容的空文本图层,强制触发Glyphs请求:style: { version: 8, sources: { osm: { /* 保留原有栅格源配置 */ }, dummy: { type: 'vector', tiles: ['https://example.com/dummy/{z}/{x}/{y}.pbf'], minzoom: 0, maxzoom: 19 } }, glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf", layers: [ { /* 保留原有栅格图层 */ }, { id: 'dummy-text-layer', type: 'symbol', source: 'dummy', layout: { 'text-field': '', 'text-font': ['Open Sans Regular'] }, paint: { 'text-color': '#000' }, filter: ['==', ['get', 'id'], 'nonexistent'] // 确保图层无内容显示 } ] }检查Angular的资源拦截与CORS配置
Angular开发服务器可能拦截了Glyphs请求,查看浏览器控制台网络面板是否有CORS错误。可通过代理配置转发请求:- 在
angular.json的serve选项中添加代理配置:"architect": { "serve": { "options": { "proxyConfig": "proxy.conf.json" } } } - 创建
proxy.conf.json文件:{ "/fonts.openmaptiles.org/*": { "target": "https://fonts.openmaptiles.org", "secure": true, "changeOrigin": true, "pathRewrite": { "^/fonts.openmaptiles.org": "" } } }
- 在
显式指定插件字体参数
初始化插件时显式传入字体配置,强制插件使用指定Glyphs资源:map.addControl(new MeasuresControl({ textFont: ['Open Sans Regular'] }), "top-left");
内容的提问来源于stack exchange,提问作者Stanislav
相关产品推荐
相关产品推荐

