From ab4980c06ba0b1467fe08c198f8b83bf13bdde7f Mon Sep 17 00:00:00 2001 From: Petr Pridal Date: Sun, 12 Aug 2012 15:47:27 +0200 Subject: [PATCH] The initial commit for 0.1pre. --- tileserver-mbtiles.php | 126 +++++++++++ tileserver-tms.php | 84 ++++++++ tileserver-wmts.php | 471 +++++++++++++++++++++++++++++++++++++++++ tileserver.php | 408 +++++++++++++++++++++++++++++++++++ 4 files changed, 1089 insertions(+) create mode 100644 tileserver-mbtiles.php create mode 100644 tileserver-tms.php create mode 100644 tileserver-wmts.php create mode 100644 tileserver.php diff --git a/tileserver-mbtiles.php b/tileserver-mbtiles.php new file mode 100644 index 0000000..9f8b508 --- /dev/null +++ b/tileserver-mbtiles.php @@ -0,0 +1,126 @@ +404 Not Found"; + echo "TileServer.php could not found what you requested."; + die(); + // TODO: if ($_GET['ext'] == 'png') { ... + // TODO: better image 256x256px !!! + // header("Content-type: image/png"); +//print("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDAT\x08\xd7c````\x00\x00\x00\x05\x00\x01^\xf3*:\x00\x00\x00\x00IEND\xaeB`\x82"); +} + +if( isset($_GET['tileset']) && preg_match('/^[\w\d_-]+$/', $_GET['tileset']) ) { + $tileset = $_GET['tileset']; + $flip = true; + try { + $db = new PDO('sqlite:'.$tileset.'.mbtiles','','',array(PDO::ATTR_PERSISTENT => true)); + if( !isset($db) ) { + header('Content-type: text/plain'); + print 'Incorrect tileset name: '.$_GET['tileset']; + exit; + } + // http://c.tile.openstreetmap.org/12/2392/1190.png + $z = floatval($_GET['z']); + $y = floatval($_GET['y']); + $x = floatval($_GET['x']); + if( $flip ) { + $y = pow(2, $z) - 1 - $y; + } + $result = $db->query('select tile_data as t from tiles where zoom_level='.$z.' and tile_column='.$x.' and tile_row='.$y); + $data = $result->fetchColumn(); + if( !isset($data) || $data === FALSE ) { + // TODO: Put here ready to use empty tile!!! + $png = imagecreatetruecolor(256, 256); + imagesavealpha($png, true); + $trans_colour = imagecolorallocatealpha($png, 0, 0, 0, 127); + imagefill($png, 0, 0, $trans_colour); + header('Content-type: image/png'); + imagepng($png); + //header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found'); + } else { + $result = $db->query('select value from metadata where name="format"'); + $resultdata = $result->fetchColumn(); + $format = isset($resultdata) && $resultdata !== FALSE ? $resultdata : 'png'; + if( $format == 'jpg' ) + $format = 'jpeg'; + header('Content-type: image/'.$format); + print $data; + } + } catch( PDOException $e ) { + header('Content-type: text/plain'); + print 'Error querying the database: '.$e->getMessage(); + } +} +/* + ?> + <?php echo htmlspecialchars($params['name']) ?> + + OSGEO:41001 + + + + + + + + + + MBTiles PHP proxy'; + if( $handle = opendir('.') ) { + $found = false; + while( ($file = readdir($handle)) !== false ) { + if( preg_match('/^[\w\d_-]+\.mbtiles$/', $file) && is_file($file) ) { + try { + $db = new PDO('sqlite:'.$file); + $params = readparams($db); + $zooms = readzooms($db); + $db = null; + print '

'.htmlspecialchars($params['name']).'

'; + if( isset($params['description']) ) + print '

'.htmlspecialchars($params['description']).'

'; + print '

Type: '.$params['type'].', format: '.$params['format'].', version: '.$params['version'].'

'; + if( isset($params['bounds']) ) + print '

Bounds: '.str_replace(',', ', ',$params['bounds']).'

'; + print '

Zoom levels: '.implode(', ', $zooms).'

'; + print '

OpenLayers: new OpenLayers.Layer.OSM("'.htmlspecialchars($params['name']).'", "'.getbaseurl().preg_replace('/\.mbtiles/','',$file).'/${z}/${x}/${y}", {numZoomLevels: '.(end($zooms)+1).', isBaseLayer: '.($params['type']=='baselayer'?'true':'false').'});

'; + print '

TMS: http://'.$_SERVER['HTTP_HOST'].preg_replace('/\/[^\/]+$/','/',$_SERVER['REQUEST_URI']).'1.0.0/'.preg_replace('/\.mbtiles/','',$file).'

'; + } catch( PDOException $e ) {} + } + } + } else { + print 'Error opening script directory.'; + } +} + +function getbaseurl() { + return 'http://'.$_SERVER['HTTP_HOST'].preg_replace('/\/(1.0.0\/)?[^\/]*$/','/',$_SERVER['REQUEST_URI']); +} +*/ +function readparams( $db ) { + $params = array(); + $result = $db->query('select name, value from metadata'); + while ($row = $result->fetch(PDO::FETCH_ASSOC)) { + $params[$row['name']] = $row['value']; + } + return $params; +} + +function readzooms( $db ) { + $zooms = array(); + $result = $db->query('select zoom_level from tiles group by zoom_level order by zoom_level'); + while ($zoom = $result->fetchColumn()) { + $zooms[] = $zoom; + } + return $zooms; +} +?> diff --git a/tileserver-tms.php b/tileserver-tms.php new file mode 100644 index 0000000..dd15b6d --- /dev/null +++ b/tileserver-tms.php @@ -0,0 +1,84 @@ +\n"; + +// Accepted GET strings +$layer = (array_key_exists('layer', $_GET)) ? $_GET['layer'] : ""; + +# ----------- +# TMS SERVICE +# ----------- +if ($layer === ""): + + $maps = maps(); +?> + + +\n"; + } + ?> + +LatLonToMeters($bounds[1], $bounds[0]); + list( $maxx, $maxy ) = $mercator->LatLonToMeters($bounds[3], $bounds[2]); + $bounds = array( $minx, $miny, $maxx, $maxy ); + $initialResolution = 156543.03392804062; + } + $format = $m['format']; + $mime = ($format == 'jpg') ? 'image/jpeg' : 'image/png'; +?> + + <?php echo htmlspecialchars($title) ?> + + + + + + + + + + + + \ No newline at end of file diff --git a/tileserver-wmts.php b/tileserver-wmts.php new file mode 100644 index 0000000..9ac1aa3 --- /dev/null +++ b/tileserver-wmts.php @@ -0,0 +1,471 @@ +\n"; ?> + + + + + OGC WMTS + 1.0.0 + + + + + + + + + + RESTful + + + + + + + + KVP + + + + + + + + + + + + + RESTful + + + + + + + KVP + + + + + + + + + + +LatLonToMeters($bounds[1], $bounds[0]); + list( $maxx, $maxy ) = $mercator->LatLonToMeters($bounds[3], $bounds[2]); + $bounds3857 = array( $minx, $miny, $maxx, $maxy ); + } + +?> + + + + + + + + + + + + + + + + + + + + + + + + + + GoogleMapsCompatible + the wellknown 'GoogleMapsCompatible' tile matrix set defined by OGC WMTS specification + GoogleMapsCompatible + urn:ogc:def:crs:EPSG:6.18:3:3857 + urn:ogc:def:wkss:OGC:1.0:GoogleMapsCompatible + + 0 + 559082264.0287178 + -20037508.34278925 20037508.34278925 + 256 + 256 + 1 + 1 + + + 1 + 279541132.0143589 + -20037508.34278925 20037508.34278925 + 256 + 256 + 2 + 2 + + + 2 + 139770566.0071794 + -20037508.34278925 20037508.34278925 + 256 + 256 + 4 + 4 + + + 3 + 69885283.00358972 + -20037508.34278925 20037508.34278925 + 256 + 256 + 8 + 8 + + + 4 + 34942641.50179486 + -20037508.34278925 20037508.34278925 + 256 + 256 + 16 + 16 + + + 5 + 17471320.75089743 + -20037508.34278925 20037508.34278925 + 256 + 256 + 32 + 32 + + + 6 + 8735660.375448715 + -20037508.34278925 20037508.34278925 + 256 + 256 + 64 + 64 + + + 7 + 4367830.187724357 + -20037508.34278925 20037508.34278925 + 256 + 256 + 128 + 128 + + + 8 + 2183915.093862179 + -20037508.34278925 20037508.34278925 + 256 + 256 + 256 + 256 + + + 9 + 1091957.546931089 + -20037508.34278925 20037508.34278925 + 256 + 256 + 512 + 512 + + + 10 + 545978.7734655447 + -20037508.34278925 20037508.34278925 + 256 + 256 + 1024 + 1024 + + + 11 + 272989.3867327723 + -20037508.34278925 20037508.34278925 + 256 + 256 + 2048 + 2048 + + + 12 + 136494.6933663862 + -20037508.34278925 20037508.34278925 + 256 + 256 + 4096 + 4096 + + + 13 + 68247.34668319309 + -20037508.34278925 20037508.34278925 + 256 + 256 + 8192 + 8192 + + + 14 + 34123.67334159654 + -20037508.34278925 20037508.34278925 + 256 + 256 + 16384 + 16384 + + + 15 + 17061.83667079827 + -20037508.34278925 20037508.34278925 + 256 + 256 + 32768 + 32768 + + + 16 + 8530.918335399136 + -20037508.34278925 20037508.34278925 + 256 + 256 + 65536 + 65536 + + + 17 + 4265.459167699568 + -20037508.34278925 20037508.34278925 + 256 + 256 + 131072 + 131072 + + + 18 + 2132.729583849784 + -20037508.34278925 20037508.34278925 + 256 + 256 + 262144 + 262144 + + + + + WGS84 + GoogleCRS84Quad + urn:ogc:def:crs:EPSG:6.3:4326 + + -180.000000 -90.000000 + 180.000000 90.000000 + + urn:ogc:def:wkss:OGC:1.0:GoogleCRS84Quad + + 0 + 279541132.01435887813568115234 + 90.000000 -180.000000 + 256 + 256 + 2 + 1 + + + 1 + 139770566.00717943906784057617 + 90.000000 -180.000000 + 256 + 256 + 4 + 2 + + + 2 + 69885283.00358971953392028809 + 90.000000 -180.000000 + 256 + 256 + 8 + 4 + + + 3 + 34942641.50179485976696014404 + 90.000000 -180.000000 + 256 + 256 + 16 + 8 + + + 4 + 17471320.75089742988348007202 + 90.000000 -180.000000 + 256 + 256 + 32 + 16 + + + 5 + 8735660.37544871494174003601 + 90.000000 -180.000000 + 256 + 256 + 64 + 32 + + + 6 + 4367830.18772435747087001801 + 90.000000 -180.000000 + 256 + 256 + 128 + 64 + + + 7 + 2183915.09386217873543500900 + 90.000000 -180.000000 + 256 + 256 + 256 + 128 + + + 8 + 1091957.54693108936771750450 + 90.000000 -180.000000 + 256 + 256 + 512 + 256 + + + 9 + 545978.77346554468385875225 + 90.000000 -180.000000 + 256 + 256 + 1024 + 512 + + + 10 + 272989.38673277234192937613 + 90.000000 -180.000000 + 256 + 256 + 2048 + 1024 + + + 11 + 136494.69336638617096468806 + 90.000000 -180.000000 + 256 + 256 + 4096 + 2048 + + + 12 + 68247.34668319308548234403 + 90.000000 -180.000000 + 256 + 256 + 8192 + 4096 + + + 13 + 34123.67334159654274117202 + 90.000000 -180.000000 + 256 + 256 + 16384 + 8192 + + + 14 + 17061.83667079825318069197 + 90.000000 -180.000000 + 256 + 256 + 32768 + 16384 + + + 15 + 8530.91833539912659034599 + 90.000000 -180.000000 + 256 + 256 + 65536 + 32768 + + + 16 + 4265.45916769956329517299 + 90.000000 -180.000000 + 256 + 256 + 131072 + 65536 + + + 17 + 2132.72958384978574031265 + 90.000000 -180.000000 + 256 + 256 + 262144 + 131072 + + + + + + \ No newline at end of file diff --git a/tileserver.php b/tileserver.php new file mode 100644 index 0000000..9d3c113 --- /dev/null +++ b/tileserver.php @@ -0,0 +1,408 @@ + array("http://10.0.1.11/"), + "serverTitle" => "TileServer.php v0.1", +); + +# PHP debugging +ini_set("error_reporting", "true"); +error_reporting(E_ALL|E_STRCT); + +# Global variable + ccepted GET / POST variables from the outside world +$baseUrl = $config['baseUrls'][0]; +// TODO: We can detext the baseUrl as well - for defined requests + +$service = (array_key_exists('service', $_GET)) ? $_GET['service'] : ""; +$layer = (array_key_exists('layer', $_GET)) ? $_GET['layer'] : ""; +$callback = (array_key_exists('callback', $_GET)) ? $_GET['callback'] : ""; + + +# ------------ +# TEST SERVICE +# ------------ +if ($service == 'test') { + header("Content-Type: text/plain; charset=utf-8"); + echo "TileServer.php (", $config['serverTitle'], ') at ', $baseUrl; + die(); +} + +# ------------ +# HTML SERVICE +# ------------ +if ($service == 'html'): + $maps = maps(); +?> + + + + + <?php echo $config['serverTitle'] ?> + +

Welcome to

+

+This server distributes maps to desktop, web, and mobile applications. +

+

+The mapping data are available as OpenGIS Web Map Tiling Service (OGC WMTS), OSGEO Tile Map Service (TMS), and popular XYZ urls described with TileJSON metadata. +

+ +

Wrong configuration of the "BaseURL" in tileserver.php

+

+Please modify 'tileserver.php' file and replace the '' in the $config variable with '' (with slash in the end) or other correct address to your server. Multiple CNAME can be used for better performance - more in readme.txt. +

+ + +

No maps available yet

+

+Ready to go - just upload some maps into directory: / on this server. +

+

+Note: The maps can be a directory with tiles in XYZ format with metadata.json file.
+You can easily convert existing geodata (GeoTIFF, ECW, MrSID, etc) to this tile structure with MapTiler Cluster or open-source projects such as GDAL2Tiles or MapTiler or simply upload any maps in MBTiles format made by TileMill. Helpful is also the mbutil tool. Serving directly from .mbtiles files is supported, but with decreased performance. +

+ +Available maps"; + echo ""; +} +?> + + + + + true)); + if (isset($db)) { + $result = $db->query('select * from metadata'); + $resultdata = $result->fetchAll(); + foreach ($resultdata as $r) { + $metadata[$r['name']] = $r['value']; + } + $metadata = metadataValidation($metadata); + $metadata['basename'] = $mbt; + } + return $metadata; +} + +function metadataValidation( $metadata ) { + if (array_key_exists('bounds', $metadata )) { + // TODO: Calculate bounds from tiles if bounds is missing - with GlobalMercator + $metadata['bounds'] = array_map( 'floatval', explode(',', $metadata['bounds'] )); + } + if (!array_key_exists('profile', $metadata )) { + $metadata['profile'] = 'mercator'; + } + // TODO: detect format, minzoom, maxzoom, thumb + // scandir() for directory / SQL for mbtiles + if (array_key_exists('minzoom', $metadata )) + $metadata['minzoom'] = intval( $metadata['minzoom'] ); + else + $metadata['minzoom'] = 0; + if (array_key_exists('maxzoom', $metadata )) + $metadata['maxzoom'] = intval( $metadata['maxzoom'] ); + else + $metadata['maxzoom'] = 18; + if (!array_key_exists('format', $metadata )) { + $metadata['format'] = 'png'; + } + /* + if (!array_key_exists('thumb', $metadata )) { + $metadata['profile'] = 'mercator'; + } + */ + return $metadata; +} + +function metadataTileJson( $metadata ) { + global $config; + $metadata['tilejson'] = '2.0.0'; + $metadata['sheme'] = 'xyz'; + $tiles = array(); + foreach($config['baseUrls'] as $url) + $tiles[] = $url.str_replace('.mbtiles', '', $metadata['basename']).'/{z}/{x}/{y}.'.$metadata['format']; + #print_r($tiles); + $metadata['tiles'] = $tiles; + return $metadata; +} + +function selfUrl( $serverOnly = false ) { + if(!isset($_SERVER['REQUEST_URI'])){ + $serverrequri = $_SERVER['PHP_SELF']; + }else{ + $serverrequri = $_SERVER['REQUEST_URI']; + } + $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : ""; + $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); + if ($serverOnly) return 'http'.$s.'://'.$_SERVER['SERVER_NAME'].$port."/"; + return 'http'.$s.'://'.$_SERVER['SERVER_NAME'].$port.$serverrequri; +} + +function doConditionalGet($timestamp) { + $last_modified = gmdate('D, d M Y H:i:s \G\M\T', $timestamp); + $etag = '"'.md5($last_modified).'"'; + // Send the headers + header("Last-Modified: $last_modified"); + header("ETag: $etag"); + // See if the client has provided the required headers + $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? + stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : + false; + $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? + stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : + false; + if (!$if_modified_since && !$if_none_match) { + return; + } + // At least one of the headers is there - check them + if ($if_none_match && $if_none_match != $etag) { + return; // etag is there but doesn't match + } + if ($if_modified_since && $if_modified_since != $last_modified) { + return; // if-modified-since is there but doesn't match + } + // Nothing has changed since their last request - serve a 304 and exit + header('HTTP/1.0 304 Not Modified'); + exit; +} + +/* +TODO: https://github.com/klokantech/tileserver-php/issues/2 + +function geoToMercTile($lon, $lat, $zoom) { + $xtile = floor((($lon + 180) / 360) * pow(2, $zoom)); + $ytile = floor((1 - log(tan(deg2rad($lat)) + 1 / cos(deg2rad($lat))) / pi()) /2 * pow(2, $zoom)); + return array($xtile, $ytile); +} + +function geoToGeoTile($lon, $lat, $zoom) { + $res = 180 / 256.0 / pow(2, $zoom); + $xtile = floor( ceil( (180 + $lat) / $res / 256.0 ) - 1 ); + $ytile = floor( ceil( (90 + $lon) / $res / 256.0 ) - 1 ); + return array($xtile, $ytile); +} + +function tileRange($bounds, $minzoom, $maxzoom) { + for ($z=$minzoom; $z < $maxzoom+1; $z++) { + print "$z\n"; + list($minx, $miny) = geoToMercTile($bounds[0], $bounds[1], $z); + list($maxx, $maxy) = geoToMercTile($bounds[2], $bounds[3], $z); + print_r( array($minx, $miny, $maxx, $maxy) ); + } +} + +// Better use the port of Klokans' GlobalMapTiles: +*/ + +/* + GlobalMapTiles - part of Aggregate Map Tools + Version 1.0 + Copyright (c) 2009 The Bivings Group + All rights reserved. + Author: John Bafford + + http://www.bivings.com/ + http://bafford.com/softare/aggregate-map-tools/ + + Based on GDAL2Tiles / globalmaptiles.py + Original python version Copyright (c) 2008 Klokan Petr Pridal. All rights reserved. + http://www.klokan.cz/projects/gdal2tiles/ + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. +*/ + +class GlobalMercator +{ + var $tileSize; + var $initialResolution; + var $originShift; + + //Initialize the TMS Global Mercator pyramid + function __construct($tileSize = 256) + { + $this->tileSize = $tileSize; + $this->initialResolution = 2 * M_PI * 6378137 / $this->tileSize; + # 156543.03392804062 for tileSize 256 Pixels + $this->originShift = 2 * M_PI * 6378137 / 2.0; + # 20037508.342789244 + } + + //Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913 + function LatLonToMeters($lat, $lon) + { + $mx = $lon * $this->originShift / 180.0; + $my = log( tan((90 + $lat) * M_PI / 360.0 )) / (M_PI / 180.0); + + $my *= $this->originShift / 180.0; + + return array($mx, $my); + } + + //Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum + function MetersToLatLon($mx, $my) + { + $lon = ($mx / $this->originShift) * 180.0; + $lat = ($my / $this->originShift) * 180.0; + + $lat = 180 / M_PI * (2 * atan( exp( $lat * M_PI / 180.0)) - M_PI / 2.0); + + return array($lat, $lon); + } + + //Converts pixel coordinates in given zoom level of pyramid to EPSG:900913 + function PixelsToMeters($px, $py, $zoom) + { + $res = $this->Resolution($zoom); + $mx = $px * $res - $this->originShift; + $my = $py * $res - $this->originShift; + + return array($mx, $my); + } + + //Converts EPSG:900913 to pyramid pixel coordinates in given zoom level + function MetersToPixels($mx, $my, $zoom) + { + $res = $this->Resolution( $zoom ); + + $px = ($mx + $this->originShift) / $res; + $py = ($my + $this->originShift) / $res; + + return array($px, $py); + } + + //Returns a tile covering region in given pixel coordinates + function PixelsToTile($px, $py) + { + $tx = ceil( $px / $this->tileSize ) - 1; + $ty = ceil( $py / $this->tileSize ) - 1; + + return array($tx, $ty); + } + + //Returns tile for given mercator coordinates + function MetersToTile($mx, $my, $zoom) + { + list($px, $py) = $this->MetersToPixels($mx, $my, $zoom); + + return $this->PixelsToTile($px, $py); + } + + //Returns bounds of the given tile in EPSG:900913 coordinates + function TileBounds($tx, $ty, $zoom) + { + list($minx, $miny) = $this->PixelsToMeters( $tx*$this->tileSize, $ty*$this->tileSize, $zoom ); + list($maxx, $maxy) = $this->PixelsToMeters( ($tx+1)*$this->tileSize, ($ty+1)*$this->tileSize, $zoom ); + + return array($minx, $miny, $maxx, $maxy); + } + + //Returns bounds of the given tile in latutude/longitude using WGS84 datum + function TileLatLonBounds($tx, $ty, $zoom) + { + $bounds = $this->TileBounds($tx, $ty, $zoom); + + list($minLat, $minLon) = $this->MetersToLatLon($bounds[0], $bounds[1]); + list($maxLat, $maxLon) = $this->MetersToLatLon($bounds[2], $bounds[3]); + + return array($minLat, $minLon, $maxLat, $maxLon); + } + + //Resolution (meters/pixel) for given zoom level (measured at Equator) + function Resolution($zoom) + { + return $this->initialResolution / (1 << $zoom); + } +} +$mercator = new GlobalMercator(); +?> \ No newline at end of file