xref: /plugin/openlayersmap/StaticMap.php (revision e4f115f428991d898eca89d760e4d9d8b2bd6495)
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/map/{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
343		$_UA = 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; '.PHP_OS.')';
344		if(function_exists("curl_init")){
345			// use cUrl
346			$ch = curl_init();
347			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
348			curl_setopt($ch, CURLOPT_USERAGENT, $_UA);
349			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
350			curl_setopt($ch, CURLOPT_URL, $url);
351			$tile = curl_exec($ch);
352			curl_close($ch);
353		} else {
354			// use file_get_contents
355			global $conf;
356			$opts = array(
357					'http'=>array(
358							'method'=>"GET",
359							'header'=>"Accept-language: en\r\n" .
360									"User-Agent: $_UA\r\n".
361									"accept: image/png\r\n",
362							'proxy' => "tcp://".$conf['proxy']['host'] . ":" . $conf['proxy']['port'],
363							'request_fulluri' => true,
364					)
365			);
366			$context = stream_context_create($opts);
367			$tile = file_get_contents($url, false, $context);
368		}
369		if($tile && $this->useTileCache){
370			$this->writeTileToCache($url,$tile);
371		}
372		return $tile;
373	}
374
375	/**
376	 * Draw gpx trace on the map.
377	 */
378	public function drawGPX(){
379		$col = imagecolorallocatealpha($this->image, 0, 0, 255, .4*127);
380		$gpxgeom = geoPHP::load(file_get_contents($this->gpxFileName),'gpx');
381		$this->drawGeometry($gpxgeom, $col);
382	}
383
384	/**
385	 * Draw kml trace on the map.
386	 */
387	public function drawKML(){
388		// TODO get colour from kml node (not currently supported in geoPHP)
389		$col = imagecolorallocatealpha($this->image, 255, 0, 0, .4*127);
390		$kmlgeom = geoPHP::load(file_get_contents($this->kmlFileName),'kml');
391		$this->drawGeometry($kmlgeom, $col);
392	}
393	/**
394	 * Draw geometry or geometry collection on the map.
395	 * @param Geometry $geom
396	 * @param int $colour drawing colour
397	 */
398	private function drawGeometry($geom, $colour){
399		switch ($geom->geometryType()) {
400			case 'GeometryCollection':
401				// recursively draw part of the collection
402				for ($i = 1; $i < $geom->numGeometries()+1; $i++) {
403					$_geom = $geom->geometryN($i);
404					$this->drawGeometry($_geom, $colour);
405				}
406				break;
407			case 'MultiPolygon':
408				// TODO implement / do nothing
409				break;
410			case 'MultiLineString':
411				// TODO implement / do nothing
412				break;
413			case 'MultiPoint':
414				// TODO implement / do nothing
415				break;
416			case 'Polygon':
417				$this->drawPolygon($geom, $colour);
418				break;
419			case 'LineString':
420				$this->drawLineString($geom, $colour);
421				break;
422			case 'Point':
423				$this->drawPoint($geom, $colour);
424				break;
425			default:
426				//draw nothing
427				break;
428		}
429	}
430
431	/**
432	 * Draw a line on the map.
433	 * @param LineString $line
434	 * @param int $colour drawing colour
435	 */
436	private function drawLineString($line, $colour){
437		imagesetthickness($this->image,2);
438		for ($p = 1; $p < $line->numGeometries(); $p++) {
439			// get first pair of points
440			$p1 = $line->geometryN($p);
441			$p2 = $line->geometryN($p+1);
442			// translate to paper space
443			$x1 = floor(($this->width/2)-$this->tileSize*($this->centerX-$this->lonToTile($p1->x(), $this->zoom)));
444			$y1 = floor(($this->height/2)-$this->tileSize*($this->centerY-$this->latToTile($p1->y(), $this->zoom)));
445			$x2 = floor(($this->width/2)-$this->tileSize*($this->centerX-$this->lonToTile($p2->x(), $this->zoom)));
446			$y2 = floor(($this->height/2)-$this->tileSize*($this->centerY-$this->latToTile($p2->y(), $this->zoom)));
447			// draw to image
448			imageline ($this->image, $x1, $y1, $x2, $y2, $colour);
449		}
450		imagesetthickness($this->image,1);
451	}
452
453	/**
454	 * Draw a point on the map.
455	 * @param Point $point
456	 * @param int $colour drawing colour
457	 */
458	private function drawPoint($point, $colour){
459		imagesetthickness($this->image,2);
460		// translate to paper space
461		$cx = floor(($this->width/2)-$this->tileSize*($this->centerX-$this->lonToTile($point->x(), $this->zoom)));
462		$cy = floor(($this->height/2)-$this->tileSize*($this->centerY-$this->latToTile($point->y(), $this->zoom)));
463		$r = 5;
464		// draw to image
465		// imageellipse($this->image, $cx, $cy,$r, $r, $colour);
466		imagefilledellipse ($this->image, $cx, $cy, $r, $r, $colour);
467		// don't use imageellipse because the imagesetthickness function has
468		// no effect. So the better workaround is to use imagearc.
469		imagearc($this->image, $cx, $cy, $r, $r, 0, 359, $colour);
470		imagesetthickness($this->image,1);
471	}
472
473	/**
474	 * Draw a polygon on the map.
475	 * @param Polygon $polygon
476	 * @param int $colour drawing colour
477	 */
478	private function drawPolygon($polygon, $colour){
479		// TODO implementation of drawing holes,
480		// maybe draw the polygon to an in-memory image and use imagecopy, draw polygon in col., draw holes in bgcol?
481
482		//print_r('Polygon:<br />');
483		//print_r($polygon);
484
485		$extPoints = array();
486		// extring is a linestring actually..
487		$extRing = $polygon->exteriorRing();
488
489		for ($i = 1; $i < $extRing->numGeometries(); $i++) {
490			$p1 = $extRing->geometryN($i);
491			$x = floor(($this->width/2)-$this->tileSize*($this->centerX-$this->lonToTile($p1->x(), $this->zoom)));
492			$y = floor(($this->height/2)-$this->tileSize*($this->centerY-$this->latToTile($p1->y(), $this->zoom)));
493			$extPoints[]=$x;
494			$extPoints[]=$y;
495		}
496		//print_r('points:('.($i-1).')<br />');
497		//print_r($extPoints);
498		//imagepolygon ($this->image, $extPoints, $i-1, $colour );
499		imagefilledpolygon($this->image, $extPoints, $i-1, $colour );
500	}
501
502	/**
503	 * add copyright and origin notice and icons to the map.
504	 */
505	public function drawCopyright(){
506		$logoBaseDir = dirname(__FILE__).'/'.'logo/';
507		$logoImg = imagecreatefrompng($logoBaseDir.$this->tileInfo['openstreetmap']['logo']);
508		$textcolor = imagecolorallocate($this->image, 0, 0, 0);
509		$bgcolor = imagecolorallocate($this->image, 200, 200, 200);
510
511		imagecopy($this->image, $logoImg, 0, imagesy($this->image)-imagesy($logoImg), 0, 0, imagesx($logoImg), imagesy($logoImg));
512		imagestring($this->image , 1, imagesx($logoImg)+2 ,imagesy($this->image)-imagesy($logoImg)+1 ,$this->tileInfo['openstreetmap']['txt'], $bgcolor );
513		imagestring($this->image , 1, imagesx($logoImg)+1 ,imagesy($this->image)-imagesy($logoImg) ,$this->tileInfo['openstreetmap']['txt'] ,$textcolor );
514
515		// additional tile source info, ie. who created/hosted the tiles
516		if ($this->maptype!='openstreetmap') {
517			$iconImg = imagecreatefrompng($logoBaseDir.$this->tileInfo[$this->maptype]['logo']);
518			imagecopy($this->image, $iconImg, imagesx($logoImg)+1, imagesy($this->image)-imagesy($iconImg), 0, 0, imagesx($iconImg), imagesy($iconImg));
519			imagestring($this->image, 1, imagesx($logoImg)+imagesx($iconImg)+4, imagesy($this->image)-ceil(imagesy($logoImg)/2)+1, $this->tileInfo[$this->maptype]['txt'], $bgcolor );
520			imagestring($this->image, 1, imagesx($logoImg)+imagesx($iconImg)+3, imagesy($this->image)-ceil(imagesy($logoImg)/2), $this->tileInfo[$this->maptype]['txt'], $textcolor );
521		}
522	}
523
524	/**
525	 * make the map.
526	 */
527	public function makeMap(){
528		$this->initCoords();
529		$this->createBaseMap();
530		if(!empty($this->markers))$this->placeMarkers();
531		if(file_exists($this->kmlFileName)) $this->drawKML();
532		if(file_exists($this->gpxFileName)) $this->drawGPX();
533		$this->drawCopyright();
534	}
535
536	/**
537	 * Calculate the lat/lon/zoom values to make sure that all of the markers and gpx/kml are on the map.
538	 * @param float $paddingFactor buffer constant to enlarge (>1.0) the zoom level
539	 */
540	private function autoZoom($paddingFactor=1.0){
541		$geoms = array();
542		$geoms[] = new Point($this->lon, $this->lat);
543		if(!empty($this->markers)){
544			foreach($this->markers as $marker){
545				$geoms[] = new Point($marker['lon'],$marker['lat']);
546			}
547		}
548		if(file_exists($this->kmlFileName)){
549			$geoms[] = geoPHP::load(file_get_contents($this->kmlFileName),'kml');
550		}
551		if(file_exists($this->gpxFileName)) {
552			$geoms[] = geoPHP::load(file_get_contents($this->gpxFileName),'gpx');
553		}
554		if (count($geoms)<=1) return;
555
556		$geom = new GeometryCollection($geoms);
557		$centroid=$geom->centroid();
558		$bbox=$geom->getBBox();
559
560		// determine vertical resolution, this depends on the distance from the equator
561		//	$vy00 = log(tan(M_PI*(0.25 + $centroid->getY()/360)));
562		$vy0 = log(tan(M_PI*(0.25 + $bbox['miny']/360)));
563		$vy1 = log(tan(M_PI*(0.25 + $bbox['maxy']/360)));
564		$zoomFactorPowered = ($this->height/2) / (40.7436654315252 * ($vy1 - $vy0));
565		$resolutionVertical = 360 / ($zoomFactorPowered * $this->tileSize);
566		// determine horizontal resolution
567		$resolutionHorizontal = ($bbox['maxx']-$bbox['minx']) / $this->width;
568		$resolution = max($resolutionHorizontal, $resolutionVertical) * $paddingFactor;
569		$zoom = log(360 / ($resolution * $this->tileSize), 2);
570
571		$this->zoom = floor($zoom);
572		$this->lon=$centroid->getX();
573		$this->lat=$centroid->getY();
574	}
575
576	/**
577	 * get the map, this may return a reference to a cached copy.
578	 * @return string url relative to media dir
579	 */
580	public function getMap(){
581		if($this->autoZoomExtent) $this->autoZoom() ;
582
583		// use map cache, so check cache for map
584		if(!$this->checkMapCache()){
585			// map is not in cache, needs to be build
586			$this->makeMap();
587			$this->mkdir_recursive(dirname($this->mapCacheIDToFilename()),0777);
588			imagepng($this->image,$this->mapCacheIDToFilename(),9);
589		}
590		$this->doc =$this->mapCacheIDToFilename();
591		// make url relative to media dir
592		return str_replace($this->mediaBaseDir, '', $this->doc);
593	}
594}
595