With the recent release of Remember the Umbrella, I wanted to create an informational graphic of where our users are located across the United States.
I was first going to dynamically create a Scaled Vector Graphic (SVG) that would change the color of the state based on the number of users currently signed up for Remember the Umbrella in that state. That was the plan until I saw a site that uses the Google Graph API to dynamically create a map of where users are logged in from. “Cool,” I thought to myself – ready to dive into creating this feature.
The Base Data
Remember the Umbrella is a fairly simple service with a fairly simple database. Basically there’s a table that has one column with all the zip codes of the users. I begin by getting all of those zip codes. These zip codes will need to be converted to states (the state that the zip code is in).
Convert Zip Codes to States
I convert each zip code into a state using the Google Maps API. I get back JSON encoded data using this URL structure:
Arrange the Data
After I have the state for each zip code, I have to assemble this into an array in the format Array([State] => Qty, …). So the data may look like this:
Array ( [WA] => 60 [MD] => 22 [NY] => 18 [TX] => 16 [CA] => 10 [MS] => 50 [WI] => 11 [MO] => 21 [NJ] => 30 [KS] => 80 [IL] => 147 )
This data is what will go into the Chart API.
Using the Google Chart API to Create the Image URL
The Google Chart API allows you to create a chart by specifying the parameters in a URL in the form:
I am using the map chart, so the first parameter is cht=map. This specifies the chart as a map.
The next parameter goes right after the word map, and is the coordinates of how to zoom in on the United States. This parameter is :fixed=20,-160,55,-35.
Then we add the size of the image that we want our map to be. This is done by the parameter chs=600×400.
So far we have:
… and now is the time that we add the colors and the states. To do this, for each state I add a color to the chco parameter (exception: the first color in chco is the color of the background) and the state ID to the chld parameter. So these parameters:
… would create a background that is gray (#cccccc) and color Illinois and Missouri #ffcccc and #ffffcc, respectively. My code loops though the states and assigns colors appropriately. A final URL for the image could look something like this:
The final product is here:
Update 6/6/2011 – jVectorMap seems to be a good way to do this as well.