When loading data directly from geojson file and using leaflet layer control have no issue. Below code works perfectly fine:
var currentSchools = new L.GeoJSON.AJAX('data/schoolWGS84.geojson');
currentSchools.addTo(mymap);
var futureSchools = new L.GeoJSON.AJAX('data/futureschoolWGS84.geojson');
futureSchools.addTo(mymap);
var baseMaps = {
"OpenStreetMap": osm,
"Stadia OSM": stadia
};
var overlays = {
"Curent Schools": currentSchools,
"Future Schools": futureSchools
};
var layerControl = L.control.layers(baseMaps, overlays).addTo(mymap);
However, when one of the geojson layer is added using jQuery.ajax, the layer is added successfully on the map but could not get the layer onto layer control: throws error at L.control.layer: Uncaught TypeError: Cannot read properties of undefined (reading 'setZIndex') The code is as below:
var currentSchools;
$.ajax({url:'LoadDataFromSQLServer.php', success:function(response){
currentSchools = L.geoJSON(JSON.parse(response));
currentSchools.addTo(mymap);
}});
I tried using callback function as stated in the thread here. The result from the callback function can only be used within the function. I need to pass the result to external variable (external to callback function e.g. rrr). One of the many codes I tried is as below:
> function currentSchools() {
> var result;
>
> $.ajax({
> url: 'LoadDataFromSQLServer.php',
> success: function(response) {
> myCallback(response);
> }
> });
>
> return result;
> }
>
> function myCallback(response) {
> L.geoJSON(JSON.parse(response)).addTo(mymap);
> }
> var rrr = currentSchools();
> alert(rrr);
I am new to this, so any help to make my code work would be appreciated.