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