You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mapbox中addSource将GeoJSON变量识别为URL致404,如何用变量加载?

Mapbox加载GeoJSON变量时避免404错误的解决方法

问题核心是你传入的geojson是JSON字符串,Mapbox的addSource方法会将字符串类型的data参数默认识别为URL地址,导致它尝试请求一个不存在的地址,从而出现404错误。

解决方法:将JSON字符串解析为JavaScript对象后再传入data参数,使用JSON.parse()方法即可完成转换。

修改后的代码示例:

this.map.on('load', () => {
  const layers = this.map!.getStyle().layers;
  const labelLayerId = layers.find(
    (layer) => layer.type === 'symbol' && layer.layout!['text-field']
  )!.id;
  const geojsonStr = '{"type": "FeatureCollection","features": [...some data]}';
  // 解析字符串为JavaScript对象
  const geojsonData = JSON.parse(geojsonStr);
  this.map!.addSource('chungbuk-data-source', {
    type: 'geojson',
    data: geojsonData
  });
});

如果你的GeoJSON数据本身就是JavaScript对象(而非字符串),可以直接传入data参数,无需额外解析:

this.map.on('load', () => {
  const layers = this.map!.getStyle().layers;
  const labelLayerId = layers.find(
    (layer) => layer.type === 'symbol' && layer.layout!['text-field']
  )!.id;
  // 直接定义为JS对象
  const geojsonData = {
    type: "FeatureCollection",
    features: [...some data]
  };
  this.map!.addSource('chungbuk-data-source', {
    type: 'geojson',
    data: geojsonData
  });
});

这样Mapbox就会将data识别为本地GeoJSON数据,而非外部URL,404问题即可解决。

内容的提问来源于stack exchange,提问作者ganggaroo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:05:14