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