Reputation: 167
I have an issue and I'm trying to solve it sine two days, so I have a list of data retrieving from postgres database, each item of this list is associate to a checkbox, so when I click a given checkbox the corresponding layer will display on map using of course Leaflet. My purpose is to create this layers dynamically to be enable to delete each layer when I uncheck its given checkbox. When I click each checkbox I can retrieve coordinates of its associated element from database to displayed on map, but when I checked a given checkbox, it always remove the last layer and not the correspondant layer of this checkbox. I hope I was clear. Any help is appreciated. You will find my code below:
Snippet of php file:
while ($row = pg_fetch_array($result))
{
echo '<div id="' . $row['nom'] . '" class="col-sm-10"><li class="Liste">' . $row['nom'] . '</li>
<div class="checkbox chk">
<label><input type="checkbox" name="id" id="DisplayCheckbox" value="' . $row['nom'] . '"></label>
</div>';
$variable=$row2['nom'];
if($result)
{
$query2 = "SELECT st_asgeojson(st_transform(geom,4326)) from domaine where nom='$variable'";
$result2 = pg_query($query2);
while ($row2 = pg_fetch_array($result2))
{
echo '<li class="Liste" name="id" style="display:none;">' . $row2[0]. '</li></div><br/>';
}
}
}
echo '</ul>'
}
?>
<script type="text/javascript">
$(document).ready(function(){
$('input[id^="DisplayCheckbox"]').on('click',function()
{
parent = $(this).val();
Item = $(this).parents('#' + parent).find("li.Liste").text();
if($(this).is(":checked"))
$.drawCategory(geoItem);
else
$.removeItem(CategoryItem);
});
});
</script>
External jquery file:
$.drawCategory = function(data)
{
dataCategory = $.parseJSON(data);
var geojsonFeature =
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": dataCategory.type,
"coordinates": dataCategory.coordinates
}
}]
};
Item=L.geoJson(geojsonFeature).addTo(map);
map.fitBounds(Item.getBounds());
};
$.removeItem = function()
{
map.removeLayer(Item);
};
Upvotes: 0
Views: 344
Reputation: 19089
it always removes the last layer and not the corresponding layer for that checkbox.
That's most probably because your code uses just one reference for the layer to be removed, and that reference is in a variable scope outside of where you expect it to be.
Also, the code is unclean, e.g. the function call is like:
$.removeItem(CategoryItem);
but CategoryItem
is not available on that scope, and furthermore the definition of that function doesn't take any arguments:
$.removeItem = function()
Clean your code and document (in the form of code comments) the inputs, effects and outputs of your functions. The underlying problem is that you don't have control over what your own code does.
Upvotes: 1