1

I get points using GeoJSON.AJAX and I want to store coordinates in array to pass it later to function that builds routes between points. Now I use this code

<script>
    function our_layers(map){

    var coords = []; //array to store coordinates
    var points = new L.GeoJSON.AJAX("{% url 'incidences' %}",{

        onEachFeature: function (feature, layer) {
            layer.bindPopup(a lot of code here);

            x = feature.geometry.coordinates
            coords.push(x);//here I add coordinates to array
        }
    });
    points.addTo(map);

    //there is button "getcoords" I created to test some things
    document.getElementById("getcoords").addEventListener("click", logCoords);

    function logCoords() {
         console.log("Test " + coords);
     }

</script>
{% leaflet_map "gis" callback="window.our_layers" %}

That way it works perfect but I need to get coords array without pressing button, obviously. But if try putting concole.log(coords) after points.addTo(map) it returns empty array. I guess it's because it need some time to calculate (because if I press button immediately after refreshing page I get empty array too). Is there any way to print array right after pushing coordinates done and without setting timeout? I also tried

        function drawPoints(p, callback) {
                    p.addTo(map);
                    callback()
                }
        function logCoords() {
                    console.log("Test " + coords);
                }

        drawPoints(points, logCoords);

But it still giving me empty array. So, is there any way to get my array without setting timeout?

0

The correct way of using Leaflet Ajax plugin is to process GeoJSON data after it has been loaded. You can use data:loaded event for that:

points.on('data:loaded', function(){
  points.addTo(map);
  // any other action on loaded data
  ....
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.