Emerson's Site


WordPress and the Google Map Charts API

When you want to have a visual, easy to use chart comparing some statistics between countries, the Google Map Geocharts is a great solution. Just pass in an array of [key, value] pairs and it will build a colored map for you. For reference, here is Google’s sample code:

google.load('visualization', '1', {'packages': ['geochart']});

  function drawRegionsMap() {
    var data = google.visualization.arrayToDataTable([
      ['Country', 'Popularity'],
      ['Germany', 200],
      ['United States', 300],
      ['Brazil', 400],
      ['Canada', 500],
      ['France', 600],
      ['RU', 700]

    var options = {};

    var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
    chart.draw(data, options);

The problem

The array that holds the map data is in JavaScript, and it was going to need to be updated on a regular basis. I really don’t feel like going back in and editing the source every time they wanted to change the data.

The WordPress Solution

One of WordPress’s redeeming qualities is the ability to do custom post types to organize different types of posts and pages. For the sake of brevity, I’ll leave it up to you to learn how to do custom post types if you don’t know already.

Because the script is inline in the PHP file, we can modify it server-side. The function to do this is quite simple:

function get_country_data() {
  $query = new WP_Query('post_type=country&posts_per_page=-1');
  $output = '[["Country","Number of LBC"]';
  if ($query->have_posts()) {
    while ($query->have_posts()) {
      $output .= ',["'.get_the_title().'",'.get_the_excerpt().']';
  $output .= ']';

  return $output;

Note that I used get_the_excerpt() instead of get_the_content() because I set up my custom post type to use the excerpt box instead of the main content box.

Once you have that function, change the var data line in the script to be:

var data = google.visualization.arrayToDataTable(<?php echo get_country_data(); ?>);

Now, anyone can easily change the content of the map through the WordPress editor, without having to rely on a developer to update it for them.


Google’s sample code is under a CC-BY license, code is © Google, Inc.