结合 geojson 和 json 制作传单

2024-01-06

我有一张带有 GeoJson 图层的 Leaflet 地图

    var objJson = "https://raw.githubusercontent.com/salucci/Leaflet-Teste/master/BrasilNovo.json";
geojsonLayer = new L.GeoJSON.AJAX(objJson, { style: style, 
    onEachFeature: onEachFeature});
    geojsonLayer.addTo(map);
    info.addTo(map);

还有一个 Ajax 请求,从本地 PHP 服务器接收 Json 数据。

$.ajax({
    url: "http://127.0.0.1/projects/phpController.php",
    type: "POST",
    dataType: "json",
    data: {"Codigo": 1100023},
    success: function(data){
        console.log(data); //here is my data
    },
    error: function(error){
         console.log("Error:");
         console.log(error);
    }
});

GeoJson 很重,所以我不想每次都在服务器上生成整个 GeoJson,想法是合并staticGeoJson 和dynamicAjax请求后通过ID(类似于SQL join)生成Json,然后将合并的对象放在Leaflet层上

GeoJson 看起来像:

{"type":"FeatureCollection","features":[
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-73,-7],[-73,-8]]]},"properties":{"field1":"value1","field2":"value2","ID":"1"}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-73,-7],[-73,-9]]]},"properties":{"field1":"value1","field2":"value2","ID":"2"}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-73,-7],[-73,-11]]]},"properties":{"field1":"value1","field2":"value2","ID":"3"}}]}

来自 Ajax 请求的 Json 如下所示:

[{"id":"1","field3":"value3","field4":"value4"},{"id":"2","field3":"value3","field4":"value4"},{"id":"3","field3":"value3","field4":"value4"}]

所以基本上我想将字段 field3 和 field4 及其值放入通过 id 连接的 GeoJson 属性中。使用 javascript 执行此操作的最佳/最快方法是什么?

有没有办法稍后在运行时合并另一个(第三个)Json?


当 Leaflet 解析您的 GeoJSON 数据并构建 GeoJSON 图层组(您已存储在您的geojsonLayer变量),它将特征数据记录到feature每个相应层的属性。

例如,在你的geojsonLayer您将得到(除其他外)一个具有以下内容的多边形:(以下称为“layer")

layer.feature.type // "Feature"
layer.feature.geometry // {"type":"Polygon","coordinates":[[[-73,-7],[-73,-8]]]}
layer.feature.properties // {"field1":"value1","field2":"value2","ID":"1"}

例如你可以这样做:

geojsonLayer.eachLayer(function (layer) {
  if (layer.feature.properties.ID === jsonObj.id) {
    for (var key in jsonObj) {
      layer.feature.properties[key] = jsonObj[key];
    }
  }
});

当然,您可以改进算法来缓存对 Leaflet 层的引用,而不必循环遍历geojsonLayer每次。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

结合 geojson 和 json 制作传单 的相关文章

随机推荐