Search code examples
javascriptjsonajaxleafletgeojson

Combining geojson and json for leaftlet


I have a Leaflet map with a GeoJson Layer on it

    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);

And also have a Ajax request that receives Json data from a local PHP server.

$.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);
    }
});

The GeoJson is a kind of heavy, so I don't want to generate de whole GeoJson on server everytime, the Idea is merge the static GeoJson and the dynamic Json by ID(something like SQL join) after the Ajax request and then put the merged object on the Leaflet Layer

The GeoJson looks like:

{"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"}}]}

And the Json from Ajax request looks like:

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

So Basically I want to put the fields field3 and field4 with their values into GeoJson properties joining by id. What's the best/fastest way to perform that using javascript?

Is there a way to merge another(third) Json later in runtime?


Solution

  • When Leaflet parses your GeoJSON data and builds a GeoJSON Layer Group (that you have stored in your geojsonLayer variable) out of it, it records the features data into the featureproperty of each corresponding layer.

    So for instance, in your geojsonLayer you will get (among others) a polygon with: (below referred to as "layer")

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

    So for example you could do:

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

    Of course you could then improve your algorithm to cache the references to your Leaflet layers, instead of having to loop through geojsonLayer every time.