Map Example

 

In the example below, the original image is an indexed file with each state colored by a different value from the palette. By converting the relative "sales data" of each state to a color value, we can use imageColorSet() to display this information graphically. The darker the blue, the more sales in that state.
<?PHP
/*
salesbystate.php
Displays a map of the US color-coded to correspond with sales data
*/

// connect to a database & load sales data into an array $states
// with the state code as the key & current sales data as value
require('salesdata.php');

$im imageCreatefrompng('usa.png') ;
// set predetermined index for each state in image usa.png
$stateIndex = array ('AL' => 16'AR' => 17'AZ' => 53'CA' => 57
                     
'CO' => 52'CT' => 37'DC' => 40'DE' => 38
                     
'FL' => 11'GA' => 10'IA' => 15'ID' =>  1
                     
'IL' => 13'IN' => 27'KS' =>  3'KY' => 26
                     
'LA' => 22'MA' => 35'MD' => 33'ME' => 28
                     
'MI' => 12'MN' =>  2'MO' =>  8'MS' => 21
                     
'MT' => 56'NC' => 18'ND' =>  7'NE' =>  4
                     
'NH' => 32'NJ' => 34'NM' => 55'NV' => 54
                     
'NY' => 19'OH' => 23'OK' =>  9'OR' => 51
                     
'PA' => 20'RI' => 39'SC' => 29'SD' =>  5
                     
'TN' => 24'TX' => 58'UT' => 63'VA' => 25
                     
'VT' => 31'WA' =>  6'WI' => 14'WV' => 30
                     
'WY' => 50 );

// convert sales data values to a color range
$normalized gradientFromRange($states);

// In order to fade from blue to white, maximize the blue component
// and then increase the other two components by the same value
foreach ($normalized as $state => $color) {
    
imageColorset($im,$stateIndex[$state],$color,$color,255) ;
}

header('Content-type: image/png'); 
imagePng($im);
imageDestroy($im);

/**
 * @return array
 * @param $usa array states
 * @desc Normalizes an aray of a range of float values to integers
 *        representing gradient color values from 0 to 255
 */
function gradientFromRange($usa) {
    
// calculate what we can outside of the for loop
    
$lowest min($usa);
    
$ratio 255 / ( max($usa) - $lowest ) ;
    foreach (
$usa as $state => $sales) {
        
// subtract the lowest sales from the current sale to zero the figure
        // then multiply by the $ratio to scale highest value to 255.
        // Subtract total from 255 since color is additive,
        // making lowest sales = highest color value (255)
        // & higest sales = lowest color value (0)
        
$gradient[$state] = 255 round(($sales $lowest) * $ratio)  ;
    }
    return 
$gradient ;
}

?>
Note that in the original image to the right, even though each state is colored with a different index, all the indexes refer to the value of white.