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.