Mapbox GL JS更新指定ID点坐标时setData报错问题咨询
Mapbox 更新点位置报错解决方法
错误根源
- 你调用
this.map.getSource("me")是错的——你创建的数据源ID是point,me是图层ID,所以拿到的不是GeoJSON类型的数据源,自然没有setData方法。 - TypeScript类型校验需要明确断言数据源类型为
GeoJSONSource,否则会提示类型错误。
解决方案1:通过setData更新整个数据源
修正数据源ID,加上类型断言,构造新的坐标数据即可:
// 获取正确的GeoJSON数据源,断言类型避免TS报错 const pointSource = this.map.getSource('point') as mapboxgl.GeoJSONSource; // 构造新的点数据 const newPointData = { type: 'FeatureCollection', features: [ { type: 'Feature', geometry: { type: 'Point', // 注意GeoJSON规范要求首字母大写 coordinates: [newLongitude, newLatitude] // 替换成你的新经纬度 }, properties: { title: 'My Point', id: 'me' } } ] }; // 更新数据源 pointSource.setData(newPointData);
解决方案2:直接修改单个Feature(更高效)
如果只想更新目标点的坐标,不需要重构整个FeatureCollection,直接修改已有Feature更高效:
const pointSource = this.map.getSource('point') as mapboxgl.GeoJSONSource; // 获取当前数据源的所有数据 const currentData = pointSource._data as GeoJSON.FeatureCollection; // 找到id为'me'的目标点 const targetFeature = currentData.features.find(feature => feature.properties?.id === 'me'); if (targetFeature) { // 更新点的坐标 (targetFeature.geometry as GeoJSON.Point).coordinates = [newLongitude, newLatitude]; // 通知Mapbox刷新数据源 pointSource.setData(currentData); }
额外修正:图层创建代码的语法错误
你创建图层时的配置对象属性间缺少逗号,会导致代码运行报错,修正后如下:
this.map.addLayer({ id: 'me', type: 'symbol', source: 'point', layout: { 'icon-image': 'custom-marker', 'icon-size': 0.05 // 原图大小的5% } });
内容的提问来源于stack exchange,提问作者duritella
相关产品推荐
相关产品推荐

