---
title: 'CSV to Geochart - Google Visualization Chart WordPress Tutorial'
url: 'https://worldoweb.co.uk/2015/csv-geochart-google-visualization-chart-wordpress-tutorial'
markdown: 'https://worldoweb.co.uk/2015/csv-geochart-google-visualization-chart-wordpress-tutorial.md'
date: '2015-12-13'
description: 'A tutorial on how to create a Google Geochart from a CSV file in WordPress. This guide covers fetching CSV data, converting it to JSON, and visualizing it using Google Visualization API in a WordPress blog.'
taxonomy:
  category:
    - 'Web Development'
    - WordPress
  tag:
    - Script
    - Tutorial
    - 'Newbies Guide'
    - Charts
    - Graphs
    - Visualization
---

# CSV to Geochart - Google Visualization Chart WordPress Tutorial

 Published on December 13, 2015 by Tracy Ridge in  [Web Development](https://worldoweb.co.uk/category/category:Web%20Development) 

 [WordPress](https://worldoweb.co.uk/category/category:WordPress) 

In this tutorial we will parse a CSV file, containing random countries, with their own colour and tooltips displaying both the country and it’s continent. The CSV file will be converted to JSON dynamically and added to a Google [Visualization](https://www.worldoweb.co.uk/tag/tag:visualization "View all my Visualization Tutorials") Geochart in your WordPress Blog.

![Geochart from CSV Tutorial ](https://worldoweb.co.uk/user/data/wp-content/uploads/geomap-from-csv.png)Image provided by [Shutterstock](https://www.shutterstock.com/pic-98703002.html "Shutterstock")

## Prerequisites

Access to your WordPress theme folder. Knowledge of PHP, JavaScript and WordPress functions is useful but not required. The CSV file can either be self-hosted or from Google Drive providing that you publish the file as a CSV and that you place it in a shared folder.

## Download

[Download CSV to Geochart](https://www.worldoweb.co.uk/user/pages/downloads/Google-Viz-Geochart-1.0.zip)

The demo CSV file can be accessed from [Google Drive](https://docs.google.com/spreadsheets/d/1fgjBUblLHTzgxlRGvcl9NFE1kaMvxQtZ-2_NNl1KKus/edit?usp=sharing). The final outcome of the Geochart will look like this.

![Geochart Finished Look](https://worldoweb.co.uk/user/data/wp-content/uploads/Geochart_Final.png)

## Let’s get Started

In the Download, among the source files, there is an example of the CSV file which we will use to create our geochart. Upload the **js** and **data** folders to your WordPress theme folder. If using a Child Theme upload to that folder and not the parent.

### Ajax in the Head

Before we start to enable our ajax event to fire when non-admin users look at the page. Open up **header.php** and check to see if **ajaxurl** is defined. If not add the following just above the **wp\_head()** function.

```php

<?php if (!is_admin()){?>;

<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

<?php }?>
```

### Add the Chart Container to the Blog Post/Page

```html
<div id="regions_div"></div>
```

### Enqueue The JavaScript and Hook in our Ajax Actions

To add the JavaScript to our WordPress blog we need to officially enqueue our scripts so that they are present for the chart to load. Open up **functions.php** and add the following and save but don’t close. Please note that if you are not using a child theme change all instances of

```php

get_stylesheet_directory_uri()

```

with

```php

get_template_directory_uri()

```

```php

//Enqueue our JS

function map_chart(){
//if (is_page('page_name')){ Highly recommend limiting to post (is_post) or page(is_page)
wp_enqueue_script('chart', 'https://www.google.com/jsapi');
wp_enqueue_script('chart_main', get_stylesheet_directory_uri(). ' /js/chart-map.js', array('jquery'));

//}
}
add_action( 'wp_enqueue_scripts', 'map_chart' );
add_action( 'wp_ajax_build_map', 'build_map' );//admin action
add_action('wp_ajax_nopriv_build_map', 'build_map');//frontend action

```

The Google Visualization library is quite heavy and unnecessary to load on every page or post. Simply un-comment **Lines 5 & 9** to only load the JavaScript on a specific page, replacing **page\_name** with the Page ID, Page Title or Page Slug. If you are displaying your chart in a blog post replace **is\_page()** with **is\_single()** See [is\_page()](https://codex.wordpress.org/Function_Reference/is_page "WordPress Codex - Is_page()") and [is\_single()](https://codex.wordpress.org/Function_Reference/is_single "WordPress Codex - is_single()") on the WP Codex for further details.

### Fetch the CSV Data

Whilst functions.php is still open we are now going to add the code snippets to fetch the data from the CSV file either in the data folder or directly from Google Drive.

```php

/*
-
- Function get_csv()
-     1. default - parse local CSV file (data folder)
-
-     2. or fetch URL of the GDrive document providing that it is in a shared folder and is published to the web as a CSV
-
- @return json encoded data
*/

function get_csv(){

//Get the CSV file - default or replace with your GDrive URL
$url = get_stylesheet_directory_uri().'/data/map_data.csv';

//$url= 'https://docs.google.com/spreadsheets/output=csv';

// Request the data from the CSV file
$request =   wp_safe_remote_get($url);
$response = wp_remote_retrieve_body( $request );

//Convert the data to an array
$data = array_map("str_getcsv", explode("n", $response));

//Count how many rows
$count = count($data);

//Use first row for names
$labels = array_shift($data);

//Use labels as keys
foreach ($labels as $label) {
  $keys[] = $label;
}
//create array with key[id]/value of count -1 as we shifted top row for headers
    for ($i = 0; $i < $count-1; $i++) {
        $idVal[]  = $i;//values
        $idKey[] = 'id';//key
        $id_array[] = array_combine($idKey,$idVal);//combine both
}

//combine the labels key with the existing data
foreach($data as $d) {
        $newArray[] = array_combine($keys, $d);
}
//Merge both arrays together
foreach($newArray as $key => $value){
    $result[$key] = array_merge($id_array[$key], $newArray[$key]);
}
//uses built-in wp_json_encode to decode data and return the result
return wp_json_encode($result);

}

/*Function build_map is fetched by the JavaScript Ajax request and uses the get_csv() function*/
function build_map(){
$data = get_csv();// gets the CSV data
echo $data;
die();
}

```

**Lines 19-20** – Requests the CSV file from the URL variable that is specified. If the file is on the server then the CSV file should be a relative link and if using Google Drive the URL will be absolute.

**Line 23** – This parses the CSV file as a string and maps it to an array.

**Line 26** – Counts how many rows are in the array.

**Line 29** – Strips the first row as headers to be used as keys in the array (Lines-32-34).

**Lines 36-40** – Creates an id array with the total count. These are used to map the colours to the right country in the JavaScript.

**Lines 43-45** – This combines the rest of the data with the labels.

**Lines 46-49** – Merge both arrays together to create 1 associative array.

**Line 51** – Converts and returns the JSON when the JavaScript executes the Build Map Ajax function (Lines-58-62).

## Chart-map.js JavaScript

The JavaScript files pulls everything together and options can be changed to suit your own preferences.

```javascript
var $j = jQuery;
var mapColor;

// Load the Visualization API and the chart package.
google.load("visualization", "1", {
  packages: ["geochart"],
});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawRegionsMap);

//Create our Chart through an Ajax request by passing the build_map action which will be parsed with the build_map function in functions.php

function drawRegionsMap() {
  $j.ajax({
    url: ajaxurl,
    data: {
      action: "build_map", //run build_map function in functions.php
    },
    dataType: "json",
  }).done(function (csv) {
    var data = new google.visualization.DataTable();
    data.addColumn("string", "Country");
    data.addColumn("number", "id"); // The id associates the color field
    data.addColumn({
      type: "string",
      role: "tooltip",
    });
    mapColor = []; //array to hold all the colours from the CSV file

    $j.each(csv, function (i, item) {
      //jquery each function

      data.addRows([
        [
          {
            v: this.countryCode,
            f: this.tooltipTitle,
          },
          this.id,
          this.tooltipText,
        ],
      ]);

      mapColor[i] = item.Color; //add each color item to the array - accessed in options below
    });
    var countColors = mapColor.length; //counts the colours - accessed in options below

    var options = {
      backgroundColor: {
        fill: "#FFFFFF",
        stroke: "#FFFFFF",
        strokeWidth: 0,
      },
      colorAxis: {
        minValue: 0,
        maxValue: countColors,
        colors: mapColor,
      },
      legend: "none",
      datalessRegionColor: "#f5f5f5",
      displayMode: "regions",
      enableRegionInteractivity: "true",
      resolution: "countries",
      sizeAxis: {
        minValue: 1,
        maxValue: 1,
        minSize: 10,
        maxSize: 10,
      },
      region: "world",
      keepAspectRatio: true,
      width: 600,
      height: 400,
      tooltip: {
        textStyle: {
          color: "#444444",
        },
        trigger: "focus",
      },
    };

    var chart = new google.visualization.GeoChart(
      document.getElementById("regions_div"),
    );

    chart.draw(data, options);
  });
}
```

**Line 16** – This is the start of the Ajax Request to build map in functions.php. As it returns the dataType JSON there is no need to decode it.

**Line 22** – Once the Ajax request is complete we start to build the chart.

**Lines 24-29** – Creates the Columns to hold our rows

**Lines 32-42** – Using jQuery’s each function we add the rows to match the columns. Line 40 represents the colours from the CSV file to be used to colour the individual countries dynamically in the options.

**Line 43** – Counts how many colours, there are, which is added to max value in options. This ensures that each country has a corresponding colour.

## Conclusion

I hope that you have enjoyed this tutorial. If you come across any errors or have any suggestions how to improve it further then please don’t hesitate to get in touch.

## Sources

- [Geochart on Google Developers](https://developers.google.com/chart/interactive/docs/gallery/geochart "Google Developers - Geochart")
- [Getting JSON out of Google Spreadsheets](https://www.ravelrumba.com/blog/json-google-spreadsheets/ "Ravel Rumba - Getting JSON out of Google Spreadsheets")

### Share

 [X](https://x.com/intent/tweet?text=CSV%20to%20Geochart%20-%20Google%20Visualization%20Chart%20WordPress%20Tutorial&url=https%3A%2F%2Fworldoweb.co.uk%2F2015%2Fcsv-geochart-google-visualization-chart-wordpress-tutorial&via=worldoweb "Share on X") [Facebook](https://www.facebook.com/sharer.php?u=https%3A%2F%2Fworldoweb.co.uk%2F2015%2Fcsv-geochart-google-visualization-chart-wordpress-tutorial "Share on Facebook") [Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fworldoweb.co.uk%2F2015%2Fcsv-geochart-google-visualization-chart-wordpress-tutorial&title=CSV%20to%20Geochart%20-%20Google%20Visualization%20Chart%20WordPress%20Tutorial "Share on Reddit") [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fworldoweb.co.uk%2F2015%2Fcsv-geochart-google-visualization-chart-wordpress-tutorial "Share on LinkedIn") [Bluesky](https://bsky.app/intent/compose?text=CSV%20to%20Geochart%20-%20Google%20Visualization%20Chart%20WordPress%20Tutorial%20https%3A%2F%2Fworldoweb.co.uk%2F2015%2Fcsv-geochart-google-visualization-chart-wordpress-tutorial "Share on Bluesky") [Email](mailto:?subject=CSV%20to%20Geochart%20-%20Google%20Visualization%20Chart%20WordPress%20Tutorial&body=https%3A%2F%2Fworldoweb.co.uk%2F2015%2Fcsv-geochart-google-visualization-chart-wordpress-tutorial "Share via email") 

#### Tags

 [ Script](https://worldoweb.co.uk/tag/tag:Script) [ Tutorial](https://worldoweb.co.uk/tag/tag:Tutorial) [ Newbies Guide](https://worldoweb.co.uk/tag/tag:Newbies%20Guide) [ Charts](https://worldoweb.co.uk/tag/tag:Charts) [ Graphs](https://worldoweb.co.uk/tag/tag:Graphs) [ Visualization](https://worldoweb.co.uk/tag/tag:Visualization) 

##### Next

 [ ← Display your WordPress Recent Posts FAQs ](https://worldoweb.co.uk/2016/display-wordpress-recent-posts-faqs) 

OR

##### Previous

 [ WOW Weekly - Sony Release PS2 Titles and Apple Open Source Swift → ](https://worldoweb.co.uk/2015/wow-weekly-sony-release-ps2-titles-apple-open-source-swift)

---

## Navigation

- Next: [WOW Weekly -  Sony Release PS2 Titles and Apple Open Source Swift](https://worldoweb.co.uk/2015/wow-weekly-sony-release-ps2-titles-apple-open-source-swift.md)
