>我有一张带有GeoJson图层的传单地图
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,这个想法是在Ajax请求之后通过ID(类似于SQL连接(合并静态GeoJson和动态Json,然后将合并的对象放在传单层上
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 和字段 4 及其值放入 GeoJson 属性中,通过 id 连接。使用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
。