Question

I need to implement a chart like geographic chart which is an image of America seperated by state by state. And then, based on data for each state, it will the chart will display state by color. For example we have

California : 20 products
Texas: 100 products
Ohio: 5 products
.....

If the number of product for a state > 20, then display that state with GREEN color, or else, display it with RED color

Until now I have no ideas how to do it. I intend to split the America Map into 50 divs and color it, but it is not effective.

Was it helpful?

Solution

There are some geo chart frameworks, for example Google Geo Chart, though it is not fully customizeable.

But you can do it by using the jVectorMap framework. Download jVectorMap 1.2.2, also choose some map of the USA (I used the Mercator and you can use the following code:

<head>
    <link rel="stylesheet" href="jquery-jvectormap-1.2.2.css" type="text/css" />
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script type="text/javascript" src="jquery-jvectormap-1.2.2.min.js"></script>
    <script type="text/javascript" src="http://jvectormap.com/js/jquery-jvectormap-us-merc-en.js"></script>
    <script type="text/javascript">
    $(function(){
        var data = { "US-CA": 20, "US-TX": 100, "US-OH": 5 };
        var colors = {};
        // create an object with colors
        for (var key in data) {
            var value = data[key];
            colors[value] = value > 20 ? "#00FF00" : "#FF0000";
        }

        $('#map_canvas').vectorMap({
            map: 'us_merc_en',
            series: {
                regions: [{
                    values: data,
                    scale: colors
                }]
            }
        });
    });
    </script>
</head>
<body>
    <div id="map_canvas" style="width: 400px; height: 300px;"></div>
</body>

The color assigning part in the for loop is quite tricky because of some limitations of the framework. Also it requires special naming for states like US-CA. But in result you will see green Texas and red California with Ohio.

Also the framework is open source and if you need some more complex functionality, you can update the code yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top