I am using getJSON to grab data from a database, which I am then displaying to a map using Leaflet.
I want to use multiple getJSON calls that I then display as different layers on the same map. My problem is how to get the callback working with multiple geoJSON calls in the getData function. Or alternatively (I'm unsure which is the better approach) - having multiple versions of the getData function and then being able to access all of them to form the layers.
For a single getJSON the following works:
function getData(callback) {
$.getJSON("getData.php", callback );
}
getData(function(data) {
let markerlist = [];
for (let i = 0; i< data.length; i++) {
let location = new L.LatLng(data[i].siteLat, data[i].siteLon);
let marker = new L.Marker(location, {
icon: myIcon,
title: 'thetitle' });
markerlist.push(marker);
}
let myLayerGroup = L.layerGroup(markerlist) // create the layer
map.addLayer(myLayerGroup); // add the layer to the map
var overlays = {"layername":myLayerGroup};
L.control.layers(baseLayers,overlays).addTo(map);
});
I have tried to follow Need callback returns multiple values in nodejs , which looks similar, but with no success.
I tried:
function getData(callback) {
let callbackString = {};
$.getJSON("getData.php", callbackString.set1);
$.getJSON("getOtherData.php", callbackString.set2);
callback(null,callbackString);
}
getData(function(data) {
let data1 = data.set1;
let data2 = data.set2;
let markerlist = [];
for (let i = 0; i< data1.length; i++) {
let location = new L.LatLng(data1[i].siteLat, data1[i].siteLon);
let marker = new L.Marker(location, {
icon: myIcon,
title: 'thetitle' });
markerlist.push(marker);
}
let myLayerGroup = L.layerGroup(markerlist) // create the layer
map.addLayer(myLayerGroup); // add the layer to the map
var overlays = {"layername":myLayerGroup};
L.control.layers(baseLayers,overlays).addTo(map);
});
which gave the error TypeError: null is not an object (evaluating 'data.set1')
I do not know where to start to have multiple versions of the getData and then access all the info in the data function.
$.getJSON("getData.php", callbackString.set1);...set1will be undefined, because you just createdcallbackStringas an empty object! I think you've misunderstood the purpose of the second argument to getJSON ... that's data that is sent in the request