Search code examples
javascriptjquerywebjqvmap

How to Change states color on jqvmap based on a Json response?


i have this map of the us and i'm

I have implemented this map of the us in a server but i'm trying to change the color of some states based on a mysql response, but i haven't been able to do it

Here's the code i have

<script type="text/javascript" src="includes/js/jquery-2.1.0.min.js">

</script>
<script src="includes/js/jquery.vmap.js"></script>
<script src="includes/js/jquery.vmap.canada.js"></script>
<script src="includes/js/jquery.vmap.usa.js"></script>

<script>
$(document).ready(function(){
    var states_colors = {};
    var states = {};
    $.post("state_service.php", function(data) {
        var states_data = data.split(',');
        for (var i = 0; i < states_data.length; i++) {
            states[i] = states_data[i].replace(/[""\[\]]+/g, '');
            states_colors[i] = states[i]+': #8EE5EE,';
        };
        console.log(states_colors);
        $('#vmap').vectorMap('set', 'colors', states_colors);
    });

    $('#vmap').vectorMap({
        map: 'usa_en',
        backgroundColor: null,
        color: '#F58025',
        hoverColor: '#754200',
        selectedColor: '#754200',
        enableZoom: false,
        showTooltip: false,
        onRegionClick: function(element, code)
        {
            var arr = [];
            arr = code.split('-');
            var url = 'search.php?';
            var query = 'keywords=&city=&state='+arr[1];
            window.location.href = url + query;
        }
    });
});
</script>

<div id="vmap" style="width: 600px; height: 600px;"></div>

And this is what the Json response brings me which are the states that i want to highlight

["AB","CO","UT"]

Solution

  • According to the docs following function is correct

    $('#vmap').vectorMap('set', 'colors', states_colors);
    

    but setColors function which takes key and color as arguments. so i changed to following, it started working

    $('#vmap').vectorMap('set', 'colors', states[i], '#8EE5EE');
    

    example : http://codepen.io/anon/pen/RPjJYb

    used following libraries for the site

    http://jqvmap.com/js/vmap/jquery.vmap.js?v=1.0
    http://jqvmap.com/js/vmap/jquery.vmap.usa.js?v=1.0