CSV to Geochart – Google Visualization Chart WordPress Tutorial

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 Geochart in your WordPress Blog.

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

Example

The demo CSV file can be accessed from Google Drive. The final outcome of the Geochart will look like this.

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.

header.php

PHP

1

2

3

4

5

<?phpif(!is_admin()){?>

<script type="text/javascript">

varajaxurl="<?php echo admin_url('admin-ajax.php'); ?>";

</script>

<?php}?>

Add the Chart Container to the Blog Post/Page

1

<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 get_stylesheet_directory_uri() with get_template_directory_uri()

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() and 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.

functions.php - Get CSV Data

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

/**

*

* 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

*/

functionget_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($labelsas$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($dataas$d){

$newArray[]=array_combine($keys,$d);

}

//Merge both arrays together

foreach($newArrayas$key=>$value){

$result[$key]=array_merge($id_array[$key],$newArray[$key]);

}

//uses built-in wp_json_encode to decode data and return the result

returnwp_json_encode($result);

}

/**

Function build_map is fetched by the JavaScript Ajax request and uses the get_csv() function

*/

functionbuild_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.

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.

Connect & Subscribe

Popular Topics

About

Did you know that WorldOWeb was initially designed to inform people on new software and security for Windows? These days I post on things I come across in the technology world, throwing in the occasional tutorial and review. Find out More

Supports

As I am a caring person I support a local charity by maintaining and designing for Alfie's Trust