Building a local tile cache using PHP

This article is written for an old version of the Virtual Earth platform. While still available for reference purposes, it is unlikely to work if implemented.

When developing Virtual Earth applications it is annoying to have to reload the map tiles every time. Why not not write a simple proxy page in PHP to cache the tiles on your local network?

Change in MapControl.js

VE_MapControl.tileUrlPrefixes=["http://h/maps/cache.php?c=0&p=",
"http://h/maps/cache.php?c=1&p=","http://h/maps/cache.php?c=2&p=",
"http://h/maps/cache.php?c=3&p="];

(h is only an alias for our development machine)

Create directories 0-3 in the "maps/" directory given above

Install HTTP_Request from the php pear repository

Place cache.php into "maps/"

<?php
$f=$_GET['c'].'/'.str_replace('?g=1','',$_GET['p']);

function pumpout($f)
{
   $expire = 10080;  // Minutes
   $exp_gmt = gmdate("D, d M Y H:i:s", time() + $expire * 60) ." GMT";
   $mod_gmt = gmdate("D, d M Y H:i:s", getlastmod()) ." GMT";
   header("Expires: " . $exp_gmt);
   header("Last-Modified: " . $mod_gmt);
   header("Cache-Control: public, max-age=" . $expire * 60);
   header('Content-Type: image/png');
   readfile($f);
}

if (file_exists($f))
{
   pumpout($f);
   exit();
}
 
require_once("pear/Request.php");

function mntffile($s)
{
	PEAR::SetErrorHandling(PEAR_ERROR_RETURN);
	$obj = &new HTTP_Request($s);
	$obj -> _timeout=5;
	
	if (@PEAR::isError(@$obj -> sendRequest())) {
		return false;
	}
	
	if ($obj -> getResponseCode()==200)
	{
		return $obj -> getResponseBody();
	}
	else
	{
		return false;
	}
}

$url='http://tiles'.$_GET['c'].'.virtualearth.msn.com/tiles/'.$_GET['p'];

$l=fopen('log','a');
fwrite($l,$url."\n");
fclose($l);

$i=0;
while (true)
{
	$data=mntffile($url);
	if ($data!=false) { break; }
	$i++;
	if ($i>5) { break; }
}

if ($data!=false)
{
	$h=fopen($f,"w");
	fwrite($h,$data);
	fclose($h);
	pumpout($f);
}

?>

Article contributed by MNT. Have you got something to contribute?

Copyright 2009. Sponsored by nsquared   |  Terms Of Use  |  Privacy Statement
Content on this site is generated from the developer community and shared freely for your enjoyment and benefit. This site is run independently of Microsoft and does not express Microsoft's views in any way.