我有一张带有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);
还有一个从本地PHP服务器接收Json数据的Ajax请求。
$.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,Idea会合并静态 GeoJson和动态在Ajax请求之后使用ID(类似于SQL连接)的Json>然后将合并的对象放在Leaflet Layer上
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?
答案 0 :(得分:0)
当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
。