0

I'm having an issue with an external js file and google maps. The external js file won't recognize an array that I created in the php file. I'm using wordpress, if that matters. In my custom template php file, I am creating a custom query:

    <?php   
        $pages = array(
            'post_type' => 'page',
            'orderby' => 'title',
            'order' => 'ASC',
            'meta_key' => '_wp_page_template',
            'meta_value'=> 'index.php'
        );

        // query results by page template
        $my_query = new WP_Query($pages);

        // array for results of custom query
        $customArray = array();

        if($my_query->have_posts()) : ?>

            <div id="listings">
                <ul>

                <?php while($my_query->have_posts()) : 
                    $my_query->the_post(); 

                    $customArray[] = array(
                    'title' => get_the_title(),
                    'lat' => get_field('latitude'),
                    'long' => get_field('longitude'),
                    'status' => get_field('status'),
                    'industry' => get_field('industry'),
                    'state' => get_field('state')
                    );
                ?>

// output the title of the post into the list
<li><?php the_title(); ?></li>

<?php endwhile; endif; ?>

                </ul>
            </div>

I'm then putting those posts into a google map as markers by converting $customArray into an actual json array called jsonarray.

var mapCanvas = document.getElementById('map-canvas');
    var mapOptions = {
      center: new google.maps.LatLng(40, -95),
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    // create the map
    var map = new google.maps.Map(mapCanvas, mapOptions);

    // convert PHP array to json
    var jsonarray = <?php echo json_encode($customArray); ?>;

    // array to hold the markers
    var markers = [];

    // Loop through our array of markers & place each one on the map  
    for( i = 0; i < 4; i++ ) {
        var position = new google.maps.LatLng(jsonarray[i]['lat'], jsonarray[i]['long']);
        var marker = new google.maps.Marker({
            position: position,
            map: map,
            icon: 'http://i.imgur.com/FPiUErC.png',
            title: jsonarray[i]['state']
        });
        markers.push(marker);
    } // end of the for loop

This works fine and the markers show up on the map. However, I want the google map script (above) to be in an external js file. So I removed the map script above and put it into an external file called map.js. I then call map.js in the footer of my php page and set it to document.ready.

The problem with putting the map script into the external js file is that my json array, var jsonarray, is no longer outputting anything. I even tried a basic alert in the map.js file, but it doesn't execute at all:

alert(jsonarray[0]['lat']);

The above alert outputs fine when the map script is in my actual php page, but it no longer outputs anything once the map script is placed in the external js page. It also disables all of the script after it since it isn't recognized. I feel like there has to be a simple reason for this. Do I have to do anything, in particular, to get this to work? It's like the external js file isn't recognizing the php array, customArray, so it's unable to convert it to the json array.

3
  • 2
    that js code is in an external .js file? In that case your php code is going to be sent as raw text to the client, without being executed, causing the entire js file to be marked as bad with syntax errors. Commented May 22, 2015 at 20:38
  • 1
    You can make a simple "hack". Simply leave the " var jsonarray....." part in a script tag in your html, and after that load the js file. The jsonarray variable will be in the global scope, and will be available in the external js file. Commented May 22, 2015 at 20:45
  • This worked, but it leads to another question/issue that I'll post below the answer that @ecarrizo posted. Commented May 23, 2015 at 5:41

2 Answers 2

3

The PHP code in the external JS file will fail because that file is not parsed by php.

Try the same approach but execute this line in the php file, so it will generate the valid value

 <script>
     var jsonarray = <?php echo json_encode($customArray); ?>;
 </script>

After that load your scripts. (it will have access to that variable because was created in the global scope).

Sign up to request clarification or add additional context in comments.

2 Comments

@Mark B This solution works. However, it leads to a different issue. I have a dropdown menu that is used to filter the wp_query. I'm using ajax to do this. Once the dropdown has been changed, I use ajax to call a PHP function containing the same custom query that is posted in the original question, but with the dropdown value passed into the query, too. After the new query runs, I need to, again, create $customArray, convert it to jsonarray, and use that info to populate the map again. However, the functions.php file won't let me run the javascript. Is there a way to do this?
Well even if the functions.php let you use javascript inside it, it would not work. If you are already making an ajax, make sure that the response returned contains the data that you need, extract it from the response and override / re assign the variable in your script and execute the corresponding method that refresh the map.
0

The function wp_localize_script() can be used to "make any data available to your script that you can normally only get from the server side of WordPress".

First of all you need to enqueue your script in functions.php (note the handle map-js):

add_action('wp_enqueue_scripts', function(){
    wp_enqueue_script( 'map-js', get_stylesheet_directory_uri().'/path/to/map.js', array(), false, true );
});

And then after the endif; on your PHP code you can put:

wp_localize_script( 'map-js', 'jsonarray', $customArray );

That passes $customArray to your script in the JavaScript variable jsonarray.


Note: I've set the $in_footer argument of wp_enqueue_script to true to delay the printing of your script, so that wp_localize_script would be called earlier to set the jsonarray variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.