Change map background when interacting with map

In this example we created a custom javascript snippet to change the background of the map when a region is clicked.


This is only possible with the Pro version of the plugin.
To achieve this you will need to do the following:

  • Add the regions and in the ‘Action Content’ field, add the URL to the image you want to associate with that region;
  • The regions added should leave the option to ‘use defaults’ enabled;
  • In the region Defaults, set the click action to ‘custom’.
  • Add the following code to the javascript custom action field:
var mapwrapper = document.getElementById('map_wrapper_20884');
mapwrapper.style.backgroundImage = "url('" + data.content + "')";
mapwrapper.style.backgroundSize = "contain";
  • Consider the map_wrapper_20884 is the id of the current map wrapper. You can change this to any other element ID on your page. 20884 in this example is the ID of the map above.

The custom code can be enhanced for improvements or to trigger any other style change.

Some screenshots of the map edit screen for the relevant options:

Change map background when interacting with map
Change map background when interacting with map

If you have any question feel free to leave a comment below or contact me.

Creating an Interactive map for Coronavirus (Covid-19)

The end of the winter of 2020 in the north hemisphere has been marked with the quick spreading of the novel Coronavirus Covid-19. At the time I’m writing this, thousands of cases are confirmed daily across the world. This is a very serious threat and we all should be careful and follow the experts advice.

Some users have been using this plugin to create interactive maps to inform people about the virus and how it is spreading geographically. I’ve decided to create this article to answer some of the most common questions and provide some examples.

There are many ways you can create a map, below is an example of a map created using 2 external sources to feed the map data to colour countries and add round markers with different sizes. We use data made available by Johns Hopkins University, copyrighted, provided to the public strictly for educational and academic research purposes. We also use data from CoronaVirus REST API v1.0, available under the GPL3 license to identify the affected countries.

Update April 1st 2020

In recent weeks the NovelCovid API became a reliable source to get the data from and therefore I updated this example accordingly. The API formats the data in such a way that we almost don’t need any custom code to make it work with the plugin, we just need to add the link to the API and adjust some of the settings. Updated map below. There’s no need to use the custom callback function I wrote below. I will still leave it in the article for reference.

Interactive Coronavirus Covid-19 Map


The above map might be cached and the data might not be updated all the time.

If you’re using the plugin, you can download this export file and import a copy of this map using the builtin WordPress import feature. Make sure to credit the sources above. The purpose of this article is not to take advantage of the current situation, but rather to help users build a map for their projects.

Other Examples

US Map divided by states with coronavirus info
USA specific Example
World Map Covid-19
Example of an older version of the map above using markers instead of colouring the countries.

Data Source

The first thing to consider is where to get the data from and how to add it to the map. The easiest way is to add the data manually. You can use the plugin interface to simply add data to the countries or create markers. This is easier if you’re gathering data for a single country or region. You can explore the builtin heatmap options or customize the map the way you want.

If you want to gather data from the hole world or a bigger region, adding all the data manually will be too much work and you might need to use external sources to feed the map. However, using external data sources will probably require some knowledge of javascript, since usually the available data is not formatted in a way that is directly compatible with the plugin.

To colour regions, the plugin is able to read CSV data in the following format, using the “Custom Data Source > Raw Data” option.

Region Code, Title, Tooltip Content, Value, Color Code;

It’s also compatible with JSON in the following format:

[
	{
		name: "California",
		id: "US-CA",
		tooltipContent: "United States - Hello California!",
		fill: "#6699cc",
		hover: "#660000",
		content: "https://california.com/",
		action: "open_url",
		value: "0",
		useDefaults: "0",
	},
	{
		name: "Texas",
		id: "US-TX",
		tooltipContent: "United States - Hello Texas!",
		fill: "#6699cc",
		hover: "#660000",
		content: "https://texas.com/",
		action: "open_url",
		value: "0",
		useDefaults: "0",
	}
]

The above sample is for regions. For markers you would also need the latitude and longitude properties.

The information below is outdated. I have now found a good reliable source. I’ll leave the information below for reference.

At the time of this writing, I couldn’t find any available data source that followed this format, so the solution is to use the custom javascript to get the existing data and format it accordingly using the custom callback sanitize option. You will need to have javascript experience, since the plugin will only provide you the possibility to run that javascript, you are responsible for the code there. I wrote a custom javascript function that does the following:

  • Use the fetch API to get the CSV made available by the Johns Hopkins University and convert the data into a JSON object compatible with the plugin.
  • Since the numbers of cases have such a high range, using the included heatmap options wouldn’t display the round markers in the best way, so I created some code to generate different sizes for the markers, based on different ranges.
  • Gets the JSON content provided by CoronaVirus REST API added as the custom data source for the regions and corrects some of the region codes to make it compatible with the map. (For example, change ‘USA’ to ‘US’, change ‘UK’ to ‘GB’, among others.

The code I wrote might not be the best and performant, but it should give you an idea of what you can do and adjust accordingly. This is the code I used:

function igm_custom_filter(data) {

let coronaMarkers;

jQuery.ajax({
  url: "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv",
  type: 'get',
	async: false, 
  dataType: 'text',
  success: function(response) {
    const lines = response.split('\n');
    const labelKeys = lines.shift().split(',');
    const output = [];
    for (let line of lines) {
			
			if(typeof line === 'string' && line.startsWith(',')){
			line = '<span></span>' + line;
			}

 			const items = line.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
			if( !Array.isArray(items)){ continue; }
      const peopleArr = items.slice(4);
			const cases = parseInt( peopleArr[peopleArr.length - 1 ] );
			
			radius = 5;

      if(cases>100){
         radius = 10;
      }

			if(cases>500){
         radius = 15;
      }

			if(cases>1000){
         radius = 20;
      }

			if(cases>5000){
         radius = 25;
      }

			if(cases>10000){
				radius = 30;
			}

      const doc = {
				'id':items[0],
				'region':items[0],
				'country':items[1],
				'latitude':parseFloat( items[2] ),
				'longitude': parseFloat( items[3] ),
				'radius':radius,
				'cases': cases,
				'fill':'rgba(221,51,51,0.47)',
				'hover':'rgba(221,51,51,0.8)',
				'useDefaults':0
			};
      output.push({ ...doc });
    }
    coronaMarkers = output;
  }
});

		data.roundMarkers = coronaMarkers;

// regions

data.regions.forEach(function(item,index){

data.regions[index].country = data.regions[index].name;

if( data.regions[index].name === 'USA') {
	data.regions[index].name = 'US';
  data.regions[index].id = 'US';
}

if( data.regions[index].name === 'UK') {
	data.regions[index].name = 'GB';
  data.regions[index].id = 'GB';
}

if( data.regions[index].name === 'S. Korea') {
	data.regions[index].name = 'KR';
  data.regions[index].id = 'KR';
}

});

    return data;
}

The code above was added in the Custom JS field for the Map. It might not be perfect, but it should provide you some guidelines to improve upon it. I used Ajax, since I know my page loads jQuery. Remember, the code added to the custom JS field is your responsibility, the plugin will only trigger it. If the map doesn’t display, you might have some javascript errors. The export file provided above includes a minified version of the code. Remember to credit the sources for the data and use it according to the licenses.

Tooltip Information

To have the map display the tooltip information with based on the data provided, we used the ‘Tooltip Template’ option. There you can use placeholders for the existing data. I ended up using the following:

{region} {country} <br> Cases: {cases}

Both the data for the markers and regions add a property in the final json called ‘cases’ and ‘country’. The ‘region’ property doesn’t always exist, but it’s left blank. Depending on your data and the available properties, you can use different placeholders.

Other Map Controls

I enabled the Zoom and Export Map controls to enhance the map. I also used the custom Legend feature to identify the 2 types of data, the infected countries and the clusters represented by the round markers.

Disclaimer

The purpose of this article is not to take advantage of the current situation, but rather to help users build a map for their projects, since some have made questions about how to create one. If you use the same data sources I mentioned, make sure to credit them. The plugin itself is not able to do everything, you will need custom Javascript, which is your responsibility. The exported map I made available above shouldn’t be used without following the licenses from the data sources.

Stay safe and use this to help others and raise awareness about this threat that is often underrated.

Feel free to leave any question in the comments below or contact us.

Live filter on map with vector icons

The challenge today was to replicate an existing map that a client already had online in a website, but needed more flexibility. Requirements:

For this project we used the overlay technique, which allows us to display multiple maps in the same base map and filter them if necessary either with a legend or an external live filter. So we create 4 maps:

  • Map for International Projects
  • Map for National Projects
  • Map for Biennials
  • Base map, with the 3 maps above in overlay

This is the result:

  • All
  • Bienals
  • International Projects
  • Nacional Projects

It’s worth noting also that we used the option to load content from a raw data source, a specific CSV format. This allowed us to import the data from the already existing map.

If you want to replicate a specific map let us know and we’ll see what we can do.

World map with UK sub-countries and Tibet overlay

There are many versions of the world map and some countries can be represented in different ways. The UK for example is represented as a unique country, but it’s made up of England, Scotland, Wales and Northern Ireland which often are required to be represented individually. For these special cases we can explore the overlay feature to display other maps in the available world map. Below we added a map of UK divided by regions and a map for the region of Tibet, to be displayed as an individual region also.

Currently the plugin doesn’t provide a map of UK divided by it’s main regions ( England, Scotland, Wales and Northern Ireland ) but this might change in the future.

To have Tibet as an individual entry, we created a map of China where we selected only the Tibet region to display. Then we used that map with a single region in the world map as an overlay.

If you have any question on how to build a map like this, feel free to leave a comment below or contact us.