[Pro] Sanitize Data – Callback Function

You are here:

You can create a custom javascript function to sanitize, modify or format the data you added to the map. The plugin will look for a javascript function called igm_custom_filter (for all maps) or igm_custom_filter_{id} (for a single map, where {id} should be the id of the map ) and if it exists it will call it passing the map data as an argument. This allows us to manipulate our data and change it if necessary with Javascript. We can simply add our javascript function to the Custom JS field.

In the example below we use custom javascript to change the color of the regions according to a value of one of the proprerties, in this case of a custom JSON source. We apply a different colour to it depending on the range of this value. We also format one of the properties to display a number divided by commas.



We used the code below to manipulate the data from the map above, to build a map with 3 colours.

function igm_custom_filter(data) {
    
    // we only want to manipulate the data from the map with id 1314
    if(data.id!=='1314'){
        return data;
    }

    data.regions = data.regions.map(function(region) {

        // set the data to not use defaults so we can use our own colours
        region.useDefaults = false;

        let pop = parseInt(region.population);

        // format number to contain commas
        region.population = igm_numberWithCommas(region.population);

        if (pop >= 50000000 && pop <= 100000000) {
            region.fill = '#31a354';
        } else if (pop > 100000000) {
            region.fill = '#006d2c';
        } else {
            region.fill = '#74c476';
        }
        return region;
    });

    return data;

}

// function to format number and add commas
function igm_numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Remember, the function could also specify which map it belongs to, having the id in the function name:

function igm_custom_filter_1234(data) {
   ...
   return data;
}

Posted by Carlos Moreira

Lead developer of Interactive Geo Maps plugin.