I have an event which after drawing a polygon on a map generate an array of Leaflet layers containing Points of Interests sitting on the polygon. This event works fine.
The point is that I would like to save this array of layers somewhere in a variable to be able to use it later on in my code. I think this is an easy issue but I am newbie with Javascript and Leaflet and not able to find out a solution. Here my code:
mymap.on('pm:create',function(e){
var jsn = e.layer.toGeoJSON().geometry;
$.ajax({
url:'load_data_testing_osm.php',
data: {id:'geojsonpol', geojsonpol:JSON.stringify(jsn)},
type:'POST',
success: function(response){
if (response.substring(0,5)=="ERROR"){
alert(response);
} else {
alert(response);
jsnPoi = JSON.parse(response);
var fromProjection = '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs';
var toProjection = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ";
var lyrPoi = L.geoJSON(jsnPoi,{coordsToLatLng:reproject, pointToLayer:returnPoiMarkerOsm});
}
},
error:function(xhr, status, error){
$('#divProjectAffected').html("ERROR: "+error);
}
});
});
I would like to use var lyrPoi later on in my code
You can easy create a global variable:
var allPOIs = [];
mymap.on('pm:create',function(e){
var jsn = e.layer.toGeoJSON().geometry;
$.ajax({
url:'load_data_testing_osm.php',
data: {id:'geojsonpol', geojsonpol:JSON.stringify(jsn)},
type:'POST',
success: function(response){
if (response.substring(0,5)=="ERROR"){
alert(response);
} else {
alert(response);
jsnPoi = JSON.parse(response);
var fromProjection = '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs';
var toProjection = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ";
var lyrPoi = L.geoJSON(jsnPoi,{coordsToLatLng:reproject, pointToLayer:returnPoiMarkerOsm});
lyrPoi.getLayers().forEach((layer)=>{
allPOIs.push(layer)
});
}
},
error:function(xhr, status, error){
$('#divProjectAffected').html("ERROR: "+error);
}
});
});
After the ajax call you have a filled allPOIs
array with all layers.
Edit
var lyrPoi = L.geoJSON(jsnPoi,{coordsToLatLng:reproject, pointToLayer:returnPoiMarkerOsm}).addTo(map);
allPOIs.forEach((layer)=>{
layer.addTo(map);
});
It is no problem if the layer added twice.