states/gd/drawtile.php

Unless stated otherwise, code available for viewing through this tool is dedicated to the public domain. If you have any questions, drop me a line.

<?php

// gif version

preg_match('#^([\w\'. ]*?)/([\d]+/[\d]+/)?([\d]+)-([\d]+)-([\d]+)\.(png|gif)$#', $_GET['tile'], $result) or die();

require('../../GoogleMapUtility.php');
require('../../../wp-config.php');  

$set = addslashes($result[1]); // came from regex; it's clean
$rect = GoogleMapUtility::getTileRect(
	$x = $result[3], // x
	$y = $result[4], // y
	$zoom = $result[5] // zoom 
);
$type = $result[6];
$savefile = $result[0];

if ($type != 'gif') die(); 

$query = "SELECT p.id, v.ordering, v.latitude, v.longitude 
FROM shape_polygons AS p LEFT JOIN shape_vertices AS v ON p.id = v.polygon_id 
WHERE p.code = '$set' AND NOT (latitude_max < $rect->y OR latitude_min > " . ($rect->y + $rect->height) . "
OR longitude_max < $rect->x OR longitude_min > " . ($rect->x + $rect->width) . ")
ORDER BY p.id, v.ordering";


try {
	$dbh = new PDO('mysql:host=mysql.uwmike.com;dbname=uwmike_maps', DB_USER, DB_PASSWORD);
	$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$points = $dbh->query($query);
} catch (PDOException $e) {
	print "Error: " . $e->getMessage();
	die();
}

ob_start(); // capture the output

if (count($points) == 0) {
	readfile('empty.gif');
} else {
	$i = 0;
	$polys = array();
	$pointlist = array();
	$pointcount = 0;
	$poly_id = 0;

	// This section loops through all the points present in the SQL result, and
	// groups them into bunches by which polygon they belong to.

	foreach($points as $row) {
		if ($poly_id != $row['id']) {
			// save old poly
			if ($pointcount > 1) {
				$polys[] = array('count' => $pointcount, 'list' => $pointlist);
			}
		
			// start new poly
			$pointlist = array();
			$pointcount = 0;
			$poly_id = $row['id'];
		}
		$point = GoogleMapUtility::toZoomedPixelCoords($row['latitude'], $row['longitude'], $zoom);
		
		$pointlist[] = $xp = $point->x - (GoogleMapUtility::TILE_SIZE * $x);
		$pointlist[] = $yp = $point->y - (GoogleMapUtility::TILE_SIZE * $y);
		$pointcount++;
	}

	if ($pointcount > 1) {
		$polys[] = array('count' => $pointcount, 'list' => $pointlist);
	}
	
	// render an actual image for this tile
	
	$im = imagecreate(GoogleMapUtility::TILE_SIZE, GoogleMapUtility::TILE_SIZE);
	
	$blank = imagecolorallocate( $im, 0, 0, 0 );
	imagefilledrectangle( $im, 0, 0, GoogleMapUtility::TILE_SIZE, GoogleMapUtility::TILE_SIZE, $blank );
	
	$red = imagecolorallocate($im, 255, 0, 0);
	
	foreach($polys as $this_poly) {
		imagefilledpolygon($im, $this_poly['list'], $this_poly['count'], $red);
	}
	
	imagecolortransparent($im, $blank);
	imagegif($im);
	imagedestroy($im);
}

header('Content-type: image/gif');

$imagedata = ob_get_flush(); // send the image to the browser

if (!is_dir("cache/$set")) mkdir("cache/$set");
file_put_contents("cache/$savefile", $imagedata);

?>