xref: /plugin/openlayersmap/StaticMap.php (revision 2d11d7004b92ab2e93b404b903474c6a6256d013)
1<?php
2/*
3 * Copyright (c) 2012 Mark C. Prins <mprins@users.sf.net>
4*
5* In part based on staticMapLite 0.03 available at http://staticmaplite.svn.sourceforge.net/viewvc/staticmaplite/
6*
7* Copyright (c) 2009 Gerhard Koch <gerhard.koch AT ymail.com>
8*
9* Licensed under the Apache License, Version 2.0 (the "License");
10* you may not use this file except in compliance with the License.
11* You may obtain a copy of the License at
12*
13*     http://www.apache.org/licenses/LICENSE-2.0
14*
15* Unless required by applicable law or agreed to in writing, software
16* distributed under the License is distributed on an "AS IS" BASIS,
17* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18* See the License for the specific language governing permissions and
19* limitations under the License.
20*/
21include_once(realpath(dirname(__FILE__)).'/../geophp/geoPHP/geoPHP.inc');
22/**
23 * @author Mark C. Prins <mprins@users.sf.net>
24 * @author Gerhard Koch <gerhard.koch AT ymail.com>
25 *
26 */
27class StaticMap {
28	// these should probably not be changed
29	protected $tileSize = 256;
30
31	// the final output
32	var $doc = '';
33
34	protected $tileInfo = array(
35			// OSM sources
36			'openstreetmap'=>array(
37					'txt'=>'(c) OpenStreetMap CC-BY-SA',
38					'logo'=>'osm_logo.png',
39					'url'=>'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'),
40			// cloudmade
41			'cloudmade' =>array(
42					'txt'=>'CloudMade tiles',
43					'logo'=>'cloudmade_logo.png',
44					'url'=> 'http://tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/2/256/{Z}/{X}/{Y}.png'),
45			'fresh' =>array(
46					'txt'=>'CloudMade tiles',
47					'logo'=>'cloudmade_logo.png',
48					'url'=> 'http://tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{Z}/{X}/{Y}.png'),
49			// OCM sources
50			'cycle'=>array(
51					'txt'=>'OpenCycleMap tiles',
52					'logo'=>'cycle_logo.png',
53					'url'=>'http://tile.opencyclemap.org/cycle/{Z}/{X}/{Y}.png'),
54			'transport'=>array(
55					'txt'=>'OpenCycleMap tiles',
56					'logo'=>'cycle_logo.png',
57					'url'=>'http://tile2.opencyclemap.org/transport/{Z}/{X}/{Y}.png'),
58			'landscape'=>array(
59					'txt'=>'OpenCycleMap tiles',
60					'logo'=>'cycle_logo.png',
61					'url'=>'http://tile3.opencyclemap.org/landscape/{Z}/{X}/{Y}.png'),
62			// H&B sources
63			'hikeandbike'=>array(
64					'txt'=>'Hike & Bike Map',
65					'logo'=>'hnb_logo.png',
66					'url'=>'http://toolserver.org/tiles/hikebike/{Z}/{X}/{Y}.png'),
67			//'piste'=>array(
68			//		'txt'=>'OpenPisteMap tiles',
69			//		'logo'=>'piste_logo.png',
70			//		'url'=>''),
71			//'sea'=>array(
72			//		'txt'=>'OpenSeaMap tiles',
73			//		'logo'=>'sea_logo.png',
74			//		'url'=>''),
75			// MapQuest
76			'mapquest'=>array(
77					'txt'=>'MapQuest tiles',
78					'logo'=>'mq_logo.png',
79					'url'=>'http://otile3.mqcdn.com/tiles/1.0.0/osm/{Z}/{X}/{Y}.png')
80	);
81	protected $tileDefaultSrc = 'openstreetmap';
82
83	// set up markers
84	protected $markerPrototypes = array(
85			// found at http://www.mapito.net/map-marker-icons.html
86			// these are 17x19 px with a pointer at the bottom left
87			'lighblue' => array('regex'=>'/^lightblue([0-9]+)$/',
88					'extension'=>'.png',
89					'shadow'=>false,
90					'offsetImage'=>'0,-19',
91					'offsetShadow'=>false
92			),
93			// openlayers std markers are 21x25px with shadow
94			'ol-marker'=> array('regex'=>'/^marker(|-blue|-gold|-green|-red)+$/',
95					'extension'=>'.png',
96					'shadow'=>'marker_shadow.png',
97					'offsetImage'=>'-10,-25',
98					'offsetShadow'=>'-1,-13'
99			),
100			// these are 16x16 px
101			'ww_icon'=> array('regex'=>'/ww_\S+$/',
102					'extension'=>'.png',
103					'shadow'=>false,
104					'offsetImage'=>'-8,-8',
105					'offsetShadow'=>false
106			),
107			// assume these are 16x16 px
108			'rest' => array('regex'=>'/^(?!lightblue([0-9]+)$)(?!(ww_\S+$))(?!marker(|-blue|-gold|-green|-red)+$)(.*)/',
109					'extension'=>'.png',
110					'shadow'=>'marker_shadow.png',
111					'offsetImage'=>'-8,-8',
112					'offsetShadow'=>'-1,-1'
113			)
114	);
115	protected $centerX, $centerY, $offsetX, $offsetY, $image;
116	protected $zoom, $lat, $lon, $width, $height, $markers, $maptype, $kmlFileName, $gpxFileName, $autoZoomExtent;
117	protected $tileCacheBaseDir, $mapCacheBaseDir, $mediaBaseDir;
118	protected $useTileCache = true;
119	protected $mapCacheID = '';
120	protected $mapCacheFile = '';
121	protected $mapCacheExtension = 'png';
122
123	/**
124	 * Constructor.
125	 * @param float $lat Latitude (x) of center of map
126	 * @param float $lon Longitude (y) of center of map
127	 * @param int $zoom Zoomlevel
128	 * @param int $width Width in pixels
129	 * @param int $height Height in pixels
130	 * @param string $maptype Name of the map
131	 * @param mixed $markers array of markers
132	 * @param string $gpx GPX filename
133	 * @param string $kml KML filename
134	 * @param string $mediaDir Directory to store/cache maps
135	 * @param string $tileCacheBaseDir Directory to cache map tiles
136	 * @param boolean $autoZoomExtent Wheter or not to override zoom/lat/lon and zoom to the extent of gpx/kml and markers
137	 */
138	public function __construct($lat, $lon, $zoom, $width, $height, $maptype, $markers, $gpx, $kml, $mediaDir, $tileCacheBaseDir, $autoZoomExtent=TRUE){
139		$this->zoom = $zoom;
140		$this->lat = $lat;
141		$this->lon = $lon;
142		$this->width = $width;
143		$this->height = $height;
144		// validate + set maptype
145		$this->maptype = $this->tileDefaultSrc;
146		if(array_key_exists($maptype,$this->tileInfo)) {
147			$this->maptype = $maptype;
148		}
149		$this->markers = $markers;
150		$this->kmlFileName = $kml;
151		$this->gpxFileName = $gpx;
152		$this->mediaBaseDir = $mediaDir;
153		$this->tileCacheBaseDir= $tileCacheBaseDir.'/olmaptiles';
154		$this->useTileCache = $this->tileCacheBaseDir !=='';
155		$this->mapCacheBaseDir = $mediaDir.'/olmapmaps';
156		$this->autoZoomExtent = $autoZoomExtent;
157	}
158
159	/**
160	 *
161	 * @param number $long
162	 * @param number $zoom
163	 * @return number
164	 */
165	public function lonToTile($long, $zoom){
166		return (($long + 180) / 360) * pow(2, $zoom);
167	}
168	/**
169	 *
170	 * @param number $lat
171	 * @param number $zoom
172	 * @return number
173	 */
174	public function latToTile($lat, $zoom){
175		return (1 - log(tan($lat * pi()/180) + 1 / cos($lat* M_PI/180)) / M_PI) /2 * pow(2, $zoom);
176	}
177
178	/**
179	 *
180	 */
181	public function initCoords(){
182		$this->centerX = $this->lonToTile($this->lon, $this->zoom);
183		$this->centerY = $this->latToTile($this->lat, $this->zoom);
184		$this->offsetX = floor((floor($this->centerX)-$this->centerX)*$this->tileSize);
185		$this->offsetY = floor((floor($this->centerY)-$this->centerY)*$this->tileSize);
186	}
187
188	/**
189	 * make basemap image.
190	 */
191	public function createBaseMap(){
192		$this->image = imagecreatetruecolor($this->width, $this->height);
193		$startX = floor($this->centerX-($this->width/$this->tileSize)/2);
194		$startY = floor($this->centerY-($this->height/$this->tileSize)/2);
195		$endX = ceil($this->centerX+($this->width/$this->tileSize)/2);
196		$endY = ceil($this->centerY+($this->height/$this->tileSize)/2);
197		$this->offsetX = -floor(($this->centerX-floor($this->centerX))*$this->tileSize);
198		$this->offsetY = -floor(($this->centerY-floor($this->centerY))*$this->tileSize);
199		$this->offsetX += floor($this->width/2);
200		$this->offsetY += floor($this->height/2);
201		$this->offsetX += floor($startX-floor($this->centerX))*$this->tileSize;
202		$this->offsetY += floor($startY-floor($this->centerY))*$this->tileSize;
203
204		for($x=$startX; $x<=$endX; $x++){
205			for($y=$startY; $y<=$endY; $y++){
206				$url = str_replace(array('{Z}','{X}','{Y}'),array($this->zoom, $x, $y), $this->tileInfo[$this->maptype]['url']);
207				$tileData = $this->fetchTile($url);
208				if($tileData){
209					$tileImage = imagecreatefromstring($tileData);
210				} else {
211					$tileImage = imagecreate($this->tileSize,$this->tileSize);
212					$color = imagecolorallocate($tileImage, 255, 255, 255);
213					@imagestring($tileImage,1,127,127,'err',$color);
214				}
215				$destX = ($x-$startX)*$this->tileSize+$this->offsetX;
216				$destY = ($y-$startY)*$this->tileSize+$this->offsetY;
217				imagecopy($this->image, $tileImage, $destX, $destY, 0, 0, $this->tileSize, $this->tileSize);
218			}
219		}
220	}
221
222	/**
223	 * Place markers on the map and number them in the same order as they are listed in the html.
224	 */
225	public function placeMarkers(){
226		$count=0;
227		$color=imagecolorallocate ($this->image,0,0,0 );
228		$bgcolor=imagecolorallocate ($this->image,200,200,200 );
229		$markerBaseDir = dirname(__FILE__).'/icons';
230		// loop thru marker array
231		foreach($this->markers as $marker){
232			// set some local variables
233			$markerLat = $marker['lat'];
234			$markerLon = $marker['lon'];
235			$markerType = $marker['type'];
236			// clear variables from previous loops
237			$markerFilename = '';
238			$markerShadow = '';
239			$matches = false;
240			// check for marker type, get settings from markerPrototypes
241			if($markerType){
242				foreach($this->markerPrototypes as $markerPrototype){
243					if(preg_match($markerPrototype['regex'],$markerType,$matches)){
244						$markerFilename = $matches[0].$markerPrototype['extension'];
245						if($markerPrototype['offsetImage']){
246							list($markerImageOffsetX, $markerImageOffsetY)  = split(",",$markerPrototype['offsetImage']);
247						}
248						$markerShadow = $markerPrototype['shadow'];
249						if($markerShadow){
250							list($markerShadowOffsetX, $markerShadowOffsetY)  = split(",",$markerPrototype['offsetShadow']);
251						}
252					}
253				}
254			}
255			// create img resource
256			if(file_exists($markerBaseDir.'/'.$markerFilename)){
257				$markerImg = imagecreatefrompng($markerBaseDir.'/'.$markerFilename);
258			} else {
259				$markerImg = imagecreatefrompng($markerBaseDir.'/marker.png');
260			}
261			// check for shadow + create shadow recource
262			if($markerShadow && file_exists($markerBaseDir.'/'.$markerShadow)){
263				$markerShadowImg = imagecreatefrompng($markerBaseDir.'/'.$markerShadow);
264			}
265			// calc position
266			$destX = floor(($this->width/2)-$this->tileSize*($this->centerX-$this->lonToTile($markerLon, $this->zoom)));
267			$destY = floor(($this->height/2)-$this->tileSize*($this->centerY-$this->latToTile($markerLat, $this->zoom)));
268			// copy shadow on basemap
269			if($markerShadow && $markerShadowImg){
270				imagecopy($this->image, $markerShadowImg, $destX+intval($markerShadowOffsetX), $destY+intval($markerShadowOffsetY),
271						0, 0, imagesx($markerShadowImg), imagesy($markerShadowImg));
272			}
273			// copy marker on basemap above shadow
274			imagecopy($this->image, $markerImg, $destX+intval($markerImageOffsetX), $destY+intval($markerImageOffsetY),
275					0, 0, imagesx($markerImg), imagesy($markerImg));
276			// add label
277			imagestring ($this->image , 3 , $destX-imagesx($markerImg)+1 , $destY+intval($markerImageOffsetY)+1 , ++$count , $bgcolor );
278			imagestring ($this->image , 3 , $destX-imagesx($markerImg) , $destY+intval($markerImageOffsetY) , $count , $color );
279		};
280	}
281	/**
282	 *
283	 * @param string $url
284	 * @return string
285	 */
286	public function tileUrlToFilename($url){
287		return $this->tileCacheBaseDir."/".str_replace(array('http://'),'',$url);
288	}
289	/**
290	 *
291	 * @param string $url
292	 */
293	public function checkTileCache($url){
294		$filename = $this->tileUrlToFilename($url);
295		if(file_exists($filename)){
296			return file_get_contents($filename);
297		}
298	}
299
300	public function checkMapCache(){
301		$this->mapCacheID = md5($this->serializeParams());
302		$filename = $this->mapCacheIDToFilename();
303		if(file_exists($filename)) return true;
304	}
305
306	public function serializeParams(){
307		return join("&",array($this->zoom,$this->lat,$this->lon,$this->width,$this->height, serialize($this->markers),$this->maptype, $this->kmlFileName, $this->gpxFileName));
308	}
309
310	public function mapCacheIDToFilename(){
311		if(!$this->mapCacheFile){
312			$this->mapCacheFile = $this->mapCacheBaseDir."/".$this->maptype."/".$this->zoom."/cache_".substr($this->mapCacheID,0,2)."/".substr($this->mapCacheID,2,2)."/".substr($this->mapCacheID,4);
313		}
314		return $this->mapCacheFile.".".$this->mapCacheExtension;
315	}
316	/**
317	 * Recursively create the directory.
318	 * @param string $pathname The directory path.
319	 * @param int $mode File access mode. For more information on modes, read the details on the chmod manpage.
320	 */
321	public function mkdir_recursive($pathname, $mode){
322		is_dir(dirname($pathname)) || $this->mkdir_recursive(dirname($pathname), $mode);
323		return is_dir($pathname) || @mkdir($pathname, $mode);
324	}
325
326	/**
327	 * Write a tile into the cache.
328	 * @param string $url
329	 * @param mixed $data
330	 */
331	public function writeTileToCache($url, $data){
332		$filename = $this->tileUrlToFilename($url);
333		$this->mkdir_recursive(dirname($filename),0777);
334		file_put_contents($filename, $data);
335	}
336	/**
337	 * Fetch a tile and (if configured) store it in the cache.
338	 * @param string $url
339	 */
340	public function fetchTile($url){
341		if($this->useTileCache && ($cached = $this->checkTileCache($url))) return $cached;
342		$ch = curl_init();
343		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
344		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; '.PHP_OS.')');
345		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
346		curl_setopt($ch, CURLOPT_URL, $url);
347		$tile = curl_exec($ch);
348		curl_close($ch);
349		if($tile && $this->useTileCache){
350			$this->writeTileToCache($url,$tile);
351		}
352		return $tile;
353	}
354
355	/**
356	 * Draw gpx trace on the map.
357	 */
358	public function drawGPX(){
359		$col = imagecolorallocatealpha($this->image, 0, 0, 255, .4*127);
360		$gpxgeom = geoPHP::load(file_get_contents($this->gpxFileName),'gpx');
361		$this->drawGeometry($gpxgeom, $col);
362	}
363
364	/**
365	 * Draw kml trace on the map.
366	 */
367	public function drawKML(){
368		// TODO get colour from kml node (not currently supported in geoPHP)
369		$col = imagecolorallocatealpha($this->image, 255, 0, 0, .4*127);
370		$kmlgeom = geoPHP::load(file_get_contents($this->kmlFileName),'kml');
371		$this->drawGeometry($kmlgeom, $col);
372	}
373	/**
374	 * Draw geometry or geometry collection on the map.
375	 * @param Geometry $geom
376	 * @param int $colour drawing colour
377	 */
378	private function drawGeometry($geom, $colour){
379		switch ($geom->geometryType()) {
380			case 'GeometryCollection':
381				// recursively draw part of the collection
382				for ($i = 1; $i < $geom->numGeometries()+1; $i++) {
383					$_geom = $geom->geometryN($i);
384					$this->drawGeometry($_geom, $colour);
385				}
386				break;
387			case 'MultiPolygon':
388				// TODO implement / do nothing
389				break;
390			case 'MultiLineString':
391				// TODO implement / do nothing
392				break;
393			case 'MultiPoint':
394				// TODO implement / do nothing
395				break;
396			case 'Polygon':
397				$this->drawPolygon($geom, $colour);
398				break;
399			case 'LineString':
400				$this->drawLineString($geom, $colour);
401				break;
402			case 'Point':
403				$this->drawPoint($geom, $colour);
404				break;
405			default:
406				//draw nothing
407				break;
408		}
409	}
410
411	/**
412	 * Draw a line on the map.
413	 * @param LineString $line
414	 * @param int $colour drawing colour
415	 */
416	private function drawLineString($line, $colour){
417		imagesetthickness($this->image,2);
418		for ($p = 1; $p < $line->numGeometries(); $p++) {
419			// get first pair of points
420			$p1 = $line->geometryN($p);
421			$p2 = $line->geometryN($p+1);
422			// translate to paper space
423			$x1 = floor(($this->width/2)-$this->tileSize*($this->centerX-$this->lonToTile($p1->x(), $this->zoom)));
424			$y1 = floor(($this->height/2)-$this->tileSize*($this->centerY-$this->latToTile($p1->y(), $this->zoom)));
425			$x2 = floor(($this->width/2)-$this->tileSize*($this->centerX-$this->lonToTile($p2->x(), $this->zoom)));
426			$y2 = floor(($this->height/2)-$this->tileSize*($this->centerY-$this->latToTile($p2->y(), $this->zoom)));
427			// draw to image
428			imageline ( $this->image, $x1, $y1, $x2, $y2, $colour);
429		}
430		imagesetthickness($this->image,1);
431	}
432
433	/**
434	 * Draw a point on the map.
435	 * @param Point $point
436	 * @param int $colour drawing colour
437	 */
438	private function drawPoint($point, $colour){
439		imagesetthickness($this->image,2);
440		// translate to paper space
441		$cx = floor(($this->width/2)-$this->tileSize*($this->centerX-$this->lonToTile($point->x(), $this->zoom)));
442		$cy = floor(($this->height/2)-$this->tileSize*($this->centerY-$this->latToTile($point->y(), $this->zoom)));
443		$r = 5;
444		// draw to image
445		// imageellipse($this->image, $cx, $cy,$r, $r, $colour);
446		imagefilledellipse ($this->image, $cx, $cy, $r, $r, $colour);
447		// don't use imageellipse because the imagesetthickness function has
448		// no effect. So the better workaround is to use imagearc.
449		imagearc($this->image, $cx, $cy, $r, $r, 0, 359, $colour);
450		imagesetthickness($this->image,1);
451	}
452
453	/**
454	 * Draw a polygon on the map.
455	 * @param Polygon $polygon
456	 * @param int $colour drawing colour
457	 */
458	private function drawPolygon($polygon, $colour){
459		// TODO implementation of drawing holes,
460		// maybe draw the polygon to an in-memory image and use imagecopy, draw polygon in col., draw holes in bgcol?
461
462		//print_r('Polygon:<br />');
463		//print_r($polygon);
464
465		$extPoints = array();
466		// extring is a linestring actually..
467		$extRing = $polygon->exteriorRing();
468
469		for ($i = 1; $i < $extRing->numGeometries(); $i++) {
470			$p1 = $extRing->geometryN($i);
471			$x = floor(($this->width/2)-$this->tileSize*($this->centerX-$this->lonToTile($p1->x(), $this->zoom)));
472			$y = floor(($this->height/2)-$this->tileSize*($this->centerY-$this->latToTile($p1->y(), $this->zoom)));
473			$extPoints[]=$x;
474			$extPoints[]=$y;
475		}
476		//print_r('points:('.($i-1).')<br />');
477		//print_r($extPoints);
478		//imagepolygon ($this->image, $extPoints, $i-1, $colour );
479		imagefilledpolygon($this->image, $extPoints, $i-1, $colour );
480	}
481
482	/**
483	 * add copyright and origin notice and icons to the map.
484	 */
485	public function drawCopyright(){
486		$logoBaseDir = dirname(__FILE__).'/'.'logo/';
487		$logoImg = imagecreatefrompng($logoBaseDir.$this->tileInfo['openstreetmap']['logo']);
488		$textcolor = imagecolorallocate($this->image, 0, 0, 0);
489		$bgcolor = imagecolorallocate($this->image, 200, 200, 200);
490
491		imagecopy($this->image, $logoImg, 0, imagesy($this->image)-imagesy($logoImg), 0, 0, imagesx($logoImg), imagesy($logoImg));
492		imagestring($this->image , 1, imagesx($logoImg)+2 ,imagesy($this->image)-imagesy($logoImg)+1 ,$this->tileInfo['openstreetmap']['txt'], $bgcolor );
493		imagestring($this->image , 1, imagesx($logoImg)+1 ,imagesy($this->image)-imagesy($logoImg) ,$this->tileInfo['openstreetmap']['txt'] ,$textcolor );
494
495		// additional tile source info, ie. who created/hosted the tiles
496		if ($this->maptype!='openstreetmap') {
497			$iconImg = imagecreatefrompng($logoBaseDir.$this->tileInfo[$this->maptype]['logo']);
498			imagecopy($this->image, $iconImg, imagesx($logoImg)+1, imagesy($this->image)-imagesy($iconImg), 0, 0, imagesx($iconImg), imagesy($iconImg));
499			imagestring($this->image, 1, imagesx($logoImg)+imagesx($iconImg)+4, imagesy($this->image)-ceil(imagesy($logoImg)/2)+1, $this->tileInfo[$this->maptype]['txt'], $bgcolor );
500			imagestring($this->image, 1, imagesx($logoImg)+imagesx($iconImg)+3, imagesy($this->image)-ceil(imagesy($logoImg)/2), $this->tileInfo[$this->maptype]['txt'], $textcolor );
501		}
502	}
503
504	/**
505	 * make the map.
506	 */
507	public function makeMap(){
508		$this->initCoords();
509		$this->createBaseMap();
510		if(count($this->markers))$this->placeMarkers();
511		if(file_exists($this->kmlFileName)) $this->drawKML();
512		if(file_exists($this->gpxFileName)) $this->drawGPX();
513		$this->drawCopyright();
514	}
515
516	/**
517	 * Calculate the lat/lon/zoom values to make sure that alle of the markers and gpx/kml are on the map.
518	 * @param float $paddingFactor buffer constant to enlarge (>1.0) the zoom level
519	 */
520	private function autoZoom($paddingFactor=1.0){
521		$geoms = array();
522		if(count($this->markers)){
523			foreach($this->markers as $marker){
524				$geoms[] = new Point($marker['lon'],$marker['lat']);
525			}
526		}
527		if(file_exists($this->kmlFileName)){
528			$geoms[] = geoPHP::load(file_get_contents($this->kmlFileName),'kml');
529		}
530		if(file_exists($this->gpxFileName)) {
531			$geoms[] = geoPHP::load(file_get_contents($this->gpxFileName),'gpx');
532		}
533		if (count($geoms)<1) return;
534		$geom = new GeometryCollection($geoms);
535		$centroid=$geom->centroid();
536		$bbox=$geom->getBBox();
537
538		// determine vertical resolution, this depends on the distance from the equator
539		//	$vy00 = log(tan(M_PI*(0.25 + $centroid->getY()/360)));
540		$vy0 = log(tan(M_PI*(0.25 + $bbox['miny']/360)));
541		$vy1 = log(tan(M_PI*(0.25 + $bbox['maxy']/360)));
542		$zoomFactorPowered = ($this->height/2.0) / (40.7436654315252 * ($vy1 - $vy0));
543		$resolutionVertical = 360 / ($zoomFactorPowered * $this->tileSize);
544		// determine horizontal resolution
545		$resolutionHorizontal = ($bbox['maxx']-$bbox['minx']) / $this->width;
546
547		$resolution = max($resolutionHorizontal, $resolutionVertical) * $paddingFactor;
548		$zoom = log(360 / ($resolution * $this->tileSize), 2);
549
550		$this->zoom = floor($zoom);
551		$this->lon=$centroid->getX();
552		$this->lat=$centroid->getY();
553	}
554
555	/**
556	 * get the map, this may return a reference to a cached copy.
557	 * @return string url relative to media dir
558	 */
559	public function getMap(){
560		if($this->autoZoomExtent) $this->autoZoom() ;
561
562		// use map cache, so check cache for map
563		if(!$this->checkMapCache()){
564			// map is not in cache, needs to be build
565			$this->makeMap();
566			$this->mkdir_recursive(dirname($this->mapCacheIDToFilename()),0777);
567			imagepng($this->image,$this->mapCacheIDToFilename(),9);
568		}
569		$this->doc =$this->mapCacheIDToFilename();
570		// make url relative to media dir
571		return str_replace($this->mediaBaseDir, '', $this->doc);
572	}
573}
574