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

Leaflet开发:如何将本地GeoJSON文件的Fetch API Promise赋值为对象

问题修复方案

你代码里存在3个可直接修复的问题:

  • 函数定义语法错误:声明getData时形参位置不能直接写字符串字面量,要换成合法变量名作为形参,实际文件路径在调用函数时传入即可
  • Promise链式调用语法错误:L.geoJSON(...).addTo(map)语句后缺少.符号,直接拼接.then()导致语法不合法
  • 弹窗逻辑错误:鼠标hover事件中需要先绑定弹窗内容再执行打开操作,你原有代码的调用顺序写反了,会导致首次hover时弹窗不显示

修正后的完整代码如下:

// 函数定义使用变量作为形参
function getData(url, cb) {
  fetch(url)
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      // 返回L.geoJSON实例给下一个then处理
      return L.geoJSON(data, {
        pointToLayer: styles_sites,
        onEachFeature: function (feature, layer) {
          // 提前绑定完整弹窗内容,避免重复绑定消耗性能
          layer.bindPopup("<b>Nombre: </b>"+feature.properties.nombre+"<br><b>Barrio: </b>"+feature.properties.barrio+"<br><b>Tipo: </b>"+feature.properties.tipo+"<br><b>Ubicacion: </b>"+feature.properties.ubicacion+"<br><b>Correo: </b>"+feature.properties.contacto);
          layer.on('mouseover', function() { 
            layer.openPopup();
          });
          layer.on('mouseout', function() { 
            layer.closePopup(); 
          });
        }
      }).addTo(map);
    })
    .then(function(result) {
      cb(result);
    });
};

getData("data/sites.geojson", function (data) {
    console.log({data});
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:27:02