I'm working on a web project that involves a dynamically generated map of the US coloring different states based on a set of data.

This SVG file gives me a good blank map of the US and is very easy to change the color of each state. The difficulty is that IE browsers don't support SVG so in order for me to use the handy syntax the svg offers, I'll need to convert it to a JPG.

Ideally, I'd like to do this with only the GD2 library but could also use ImageMagick. I have absolutely no clue how to do this.

Any solution that would allow me to dynamically change the colors of states on a map of the US will be considered. The key is that it is easy to change the colors on the fly and that it is cross browser. PHP/Apache solutions only, please.

Thanks!

Comments

are there any classes designed to port SVG over to VML? that way you could still have a 'HTML5'-type solution

Written by Patrick

take a look at my answer. exactly what you need

Written by James Eggers

Accepted Answer

That's funny you asked this, I just did this recently for my work's site and I was thinking I should write a tutorial... Here is how to do it with ImageMagick:

$usmap = '/path/to/blank/us-map.svg';
$im = new Imagick();
$svgin = file_get_contents($usmap);

/*loop to color each state as needed, something like 
1)explode $svgin
2)foreach($array as $state){preg_replace blank color->state color }
3)implode to $svgout*/

$im->readImageBlob($svgout);

/*png settings*/
$im->setImageFormat("png24");
$im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1);  /*Optional, if you need to resize*/

/*jpeg*/
$im->setImageFormat("jpeg");
$im->adaptiveResizeImage(720, 445); /*Optional, if you need to resize*/

$im->writeImage('/path/to/colored/us-map.png');/*(or .jpg)*/
$im->clear();
$im->destroy();

the steps 1-3 vary depending on the svg and how the id & color values are stored. If you dont want to store a file on the server, you can output the image as base 64 like

<?php echo '<img src="data:image/jpg;base64,' . base64_encode($im) . '"  />';?>

(before you use clear/destroy) but ie has issues with PNG as base64 so you'd probably have to output base64 as jpeg

you can see an example here:

Start: http://upload.wikimedia.org/wikipedia/commons/3/32/Blank_US_Map.svg

Finish: http://www.foamtecintlwcc.com/contact/cs-north-america.html (upper map)

Written by WebChemist
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki