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?

indeedme
  • 25
  • 8
  • See https://stackoverflow.com/questions/42564103/ajax-and-leaflet-inspect-feature-properties-before-styling-adding-to-map/42572606?r=SearchResults#42572606 – ghybs May 24 '19 at 17:50

1 Answers1

0

Solution is

points.on('data:loaded', function () {
            points.addTo(map);
            logCoords();
        });
indeedme
  • 25
  • 8