How to query multiple php values into a javascript variable

I am using a php while statement to query latitude and longitude coordinates into a javascript variable. As of now it gets queried into separate js variables like

  var locations = [
     [ "59.911968", "10.709821" ]
                  ];
  var locations = [
     [ "57.701476", "11.97373" ]
                  ];

But Im trying to get it like

Read More
   var locations = [
     [ "59.911968", "10.709821" ]
     [ "57.701476", "11.97373" ]
                  ];

The while statement:

<?php
   $args = array('post_type' => 'events');
   $my_query = new WP_Query($args);
        while ($my_query->have_posts()) : $my_query->the_post();  
            $lat  = get_field( "gp_latitude" ); 
            $lon  = get_field( "gp_longitude" ); 
?>
<script>
    var locations = [
     [ <?php echo json_encode($lat) ?>, <?php echo json_encode($lon) ?> ]
    ];
</script>

<?php endwhile; ?>

Related posts

2 comments

  1. json_encode supports complex values, you can do:

    <?php
       $args = array('post_type' => 'events');
       $my_query = new WP_Query($args);
            locations = array();
            while ($my_query->have_posts()) : $my_query->the_post();
                $locations[] = array(
                    "lat" => get_field( "gp_latitude" ),
                    "lng" => get_field( "gp_longitude" ),
                );
    endwhile; ?>
    <script>
        var locations = <?php echo json_encode($locations) ?>;
    </script>
    

    I may have messed up the while-loop syntax. The idea is that you collect all the values in $locations and then export it to JavaScript once.

  2. You want to declare the var locations = [] out of the loop and after push each location to the array like:

    locations.push([ <?php echo json_encode($lat) ?>, <?php echo json_encode($lon) ?> ]);
    

    or even easier create the locations as an php array and json_encode it!

Comments are closed.