PHP DevCenter
oreilly.comSafari Books Online.Conferences.


Trip Mapping with PHP
Pages: 1, 2


We need a map on which to draw red lines. The Institute for the Study of the Continents at Cornell University has an Interactive Mapping Tool that we can use. Adjusting the map extent and turning on state borders produces the map shown in Figure 1.

Figure 1 - a US map with state borders

To turn longitude and latitude into a spot in the image, you need to translate a coordinate from longitude and latitude into x and y coordinates. The map in Figure 1 runs from -125 degrees longitude to -67 degrees longitude and is 602 pixels wide. This means that -125 degrees longitude has an x coordinate of 0, and -67 degrees longitude has an x coordinate of 601. Since 602 pixels represent 58 degrees of longitude, 1 degree of longitude corresponds to about 10.4 pixels (602 / 58). In latitude, the map runs from 23 degrees to 50 degrees and is 324 pixels high. Twelve pixels represent 1 degree of latitude (324 / (50 - 23)).

Using this logic, the latlon_to_pix() function translates latitude and longitude to x and y coordinates. The range of x and y coordinates in the image are set in $x_min, $x_max, $y_min, and $y_max. The range of latitude and longitude are set in $lon_min, $lon_max, $lat_min, and $lat_max. To simplify calculations, the latitude signs have been switched from negative to positive.

function latlon_to_pix($lat,$lon) {
	$lat = abs($lat);
	$lon = abs($lon);

	$x_min   = 0;  $x_max   = 602;
	$y_min   = 0;  $y_max   = 324;
	$lon_min = 67; $lon_max = 125;
	$lat_min = 23; $lat_max = 50;

	$x = $x_min + ($x_max - $x_min) * 
		( 1 - ($lon - $lon_min) / ($lon_max - $lon_min) );
	$y = $y_max - ($y_max - $y_min) * 
		( ($lat - $lat_min) / ($lat_max - $lat_min) );
	return array(intval($x),intval($y));


With the data in the database and an appropriate map, you have all of the ingredients to create the image. The image display code follows. If it's not passed any ZIP codes, it displays a form to gather them.

// parse any ZIP codes in $_REQUEST['zip'] into an array
$zips = preg_split('/[^0-9]+/',$_REQUEST['zip'], 
                   -1, PREG_SPLIT_NO_EMPTY);

if (count($zips)) {
	$dbh = DB::connect('mysql://test:@localhost/test') 
		or die($php_errormsg);
	DB::isError($dbh) and die(print_r($dbh));

	$im = imagecreatefromjpeg('us.jpg');
	$red = imagecolorallocate($im,255,0,0);
	$x1 = $y1 = null;
	foreach ($zips as $zip) {
		$row = $dbh->getRow(
			'SELECT lat,lon FROM zcta WHERE zip LIKE ?',
			and die("Can't get coordinates for $zip");
			and die("No coordinates for $zip");
		list($x,$y) = latlon_to_pix($row[0],$row[1]);
		if (is_null($x1) && is_null($y1)) {
			$x1 =$x; $y1 = $y;
		} else {
			$x1 = $x; $y1 = $y;
	header('Content-type: image/jpeg');
} else {
<form method="post" action="$_SERVER[PHP_SELF]">
Enter some ZIP Codes to have the path between them mapped:
<textarea name="zip" rows="4" cols="40"></textarea>
<input type="submit" value="Map It!">

If $_REQUEST['zip'] contains ZIP codes (parsed by preg_split()), then $dbh and $im will contain a database connection and an image handle, respectively. Using imagecreatefromjpeg() loads us.jpg and returns a handle so you can draw lines on the image. After adding red to the color palette with imagecolorallocate(), call imagesetthickness() so that the lines drawn are bold on the map. Then, loop through each ZIP code and retrieve its latitude and longitude from the database. If $row contains latitude and longitude coordinates, translate them to x and y coordinates with latlon_to_pix() and draw a line with imageline(). Each time through the loop, the newly generated x and y coordinates are saved in $x1 and $y1. These become the starting point of the line the next time through the loop. The first time through the loop, no line is drawn, but the coordinates are saved for the next iteration.

After all the lines are drawn, header() tells the browser to expect a JPEG image. imagejpeg() sends the image data to the browser. imagedestroy() frees the memory allocated for the image.

Figure 2 - our circuitous tripometer

The map shown in Figure 2 is a trip from ZIP code 19151 (Philadelphia, PA) to 60615 (Chicago, IL) to 33433 (Boca Raton, FL) to 98052 (Redmond, WA) to 95472 (Sebastopol, CA). The ZIP codes, their longitudes, latitudes, x, and y coordinates are:

ZIP code Longitude Latitude x y

The Census data file contains lots of additional information that might make interesting extensions to this program, such as drawing circles with diameters proportional to the population at each ZIP code. You could also calculate the total distance traveled using the code at

David Sklar is an independent consultant in New York City, the author of O'Reilly's Learning PHP 5, and a coauthor of PHP Cookbook.

O'Reilly & Associates will soon release (November 2002) PHP Cookbook .

Return to the PHP DevCenter.

Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!

Sponsored by: