Leaflet put coordinates of every point in array

by indeedme   Last Updated May 24, 2019 18:22 PM

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?



Related Questions


Updated February 20, 2017 13:22 PM

Updated May 29, 2017 09:22 AM

Updated June 26, 2017 08:22 AM

Updated April 03, 2019 15:22 PM