WordPress query_posts inside Google Maps API javascript (multiple markers)

Is it possible, inside the Google Maps javascript API, to query all WordPress posts for their latitude and longitude locations stored as custom fields, to display all markers on the same map?

var locations = [
<?php query_posts('post_type=property&showposts=9999999');?>
<?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>
['<?php the_title(); ?>', <?php echo get_post_meta( $post->ID, 'latitude', true ); ?>, <?php echo get_post_meta( $post->ID, 'longitude', true ); ?>, <?php the_ID(); ?>],
<?php endwhile; else: ?>
<?php endif; ?>
];

I tried this, but it cuts off after the initial bracket [ when loaded.

Related posts

Leave a Reply

2 comments

  1. I’ve done something similar here. My approach was to use the WordPress wp_localize_script function to generate the parameters, which I think would be your best option.

    I don’t have time to pull code out right now, but if you need more I can look later.

    Edit

    Ok, here you go. This is all based on the link above, so it may have a little more code than you need, but it should do the trick.

    First, I created a custom post type called property to match your code, and created a couple of properties, giving each a latitude and longitude.

    Next I created a file called so.maps.js, with the following content (the bounds code is just to make sure the map shows all my markers; you may not need it):

    (function($) {
        function initialise_map() {
            var locations_str = php_args.locations.replace(/&quot;/g, '"');
            var locations = $.parseJSON(locations_str);
    
            var latlng = new google.maps.LatLng(48.856667, 2.350833);
            var myOptions = {
                zoom: 2,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
    
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
            var bounds = new google.maps.LatLngBounds();
            for (var i = 0; i < locations.length; i++) {
                addMarker(locations[i], map, bounds);
            }
    
            if (locations.length > 1) {
                map.fitBounds(bounds);
            }
        }
    
        function addMarker(location, map, bounds) {
            var locationLatLng = new google.maps.LatLng(location.latitude,location.longitude);
            bounds.extend(locationLatLng);
            var marker = new google.maps.Marker({
                position: locationLatLng,
                map: map,
                title:location.title
            });
        }
    
        $(function() {
            initialise_map();
        });
    
    })(jQuery);
    

    The important part is the php_args variable – that’s what’s populated by the wp_localize_script call I mentioned earlier.

    Then I created a page to show the map, populating the array I wanted to pass to the JavaScript and passing it with wp_localize_script:

    <?php
     /*
      Template Name: Test Page
     */
    
    define('GOOGLE_MAPS_V3_API_KEY', 'xxxxx');
    
    add_action('wp_enqueue_scripts', 'so_exhibitions_map_scripts');
    function so_exhibitions_map_scripts() {
        wp_register_script('googlemaps', 'http://maps.googleapis.com/maps/api/js?hl=en&key=' . GOOGLE_MAPS_V3_API_KEY . '&sensor=false', false, '3');
        wp_enqueue_script('googlemaps');
    
        wp_register_script( 'so.maps', get_bloginfo('stylesheet_directory') . "/js/so.maps.js", array('jquery', 'googlemaps'), false, false );
        wp_enqueue_script('so.maps');
    
        $locations = array();
    
        $location_query = new WP_Query( array(
            'post_type' => 'property',
            'posts_per_page' => -1
        ) );
    
        while ( $location_query->have_posts() ) {
            $location_query->the_post();
            $locations[] = array(
                'title' => get_the_title(),
                'latitude' => get_post_meta( get_the_ID(), 'latitude', true ),
                'longitude' => get_post_meta( get_the_ID(), 'longitude', true ),
                'id' => get_the_ID()
            );
        }
    
        wp_reset_postdata();
    
        wp_localize_script('so.maps', 'php_args', array(
            'locations' => json_encode($locations)
        ));
    }
    
    get_header();
    ?>
            <div id="container">
                <div id="content">
                    <div id="map_canvas"></div>
                </div><!-- #content -->
            </div><!-- #container -->
    <?php
    get_footer();
    ?>
    

    Finally, I made sure the map was visible by setting its size in the CSS:

    #map_canvas {
        width: 100%;
        height: 452px;
    }
    

    Hope that helps. I’m no expert on the Google Maps API, but this did the trick for me.

  2. Thanks for your continued help! We sort of combined your code with our previous code, below is the code we ultimately used to make it work properly. However, it seems to timeout if you raise the post query to an amount greater than 200 markers. I’m not sure how to avoid this from happening, because according to Google there is no limit on their end. PHP/Apache limits have been raised, but it didn’t help. A friend suggested its probably a javascript problem. If anyone has further suggestions on allowing larger queries, please comment. 🙂

    <div id="map" style="width:960px;height:1200px;"></div>
    
    <script type="text/javascript">
    <?php
    $locations = array();
    $location_query = new WP_Query( array(
    'post_type' => 'property',
    'posts_per_page' => 100
     ) );
    echo "//markers: 100n";
    echo "var locations = [";
    $comma = "";
    while ( $location_query->have_posts() ) {
    $location_query->the_post();
    $title = str_replace("'", "'", get_the_title());
    echo $comma . "['" . $title . "', '" . get_post_meta( get_the_ID(), 'latitude', true ) . "', '" . get_post_meta( get_the_ID(), 'longitude', true ) . "', " . get_the_id() . "]";  
    $comma = ", ";
    }
    echo "];nn";
    ?>
    
    var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: new google.maps.LatLng(X.XXX, X.XXX),
    mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    
    var infowindow = new google.maps.InfoWindow();
    
    var marker, i;
    
    for (i = 0; i < locations.length; i++) {  
    marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
    });
    
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
    infowindow.setContent(locations[i][0]);
    infowindow.open(map, marker);
    }
    })(marker, i));
    }
    </script>