xref: /plugin/openlayersmap/StaticMap.php (revision c8eb13626ece0cdbb2369662b8c76ea8fa800c3a)
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
246				$tileData = $this->fetchTile ( $url );
247				if ($tileData) {
248					$tileImage = imagecreatefromstring ( $tileData );
249				} else {
250					$tileImage = imagecreate ( $this->tileSize, $this->tileSize );
251					$color = imagecolorallocate ( $tileImage, 255, 255, 255 );
252					@imagestring ( $tileImage, 1, 127, 127, 'err', $color );
253				}
254				$destX = ($x - $startX) * $this->tileSize + $this->offsetX;
255				$destY = ($y - $startY) * $this->tileSize + $this->offsetY;
256				dbglog($this->tileSize,"imagecopy tile into image: $destX, $destY");
257				imagecopy ( $this->image, $tileImage, $destX, $destY, 0, 0, $this->tileSize, $this->tileSize );
258			}
259		}
260	}
261
262	/**
263	 * Place markers on the map and number them in the same order as they are listed in the html.
264	 */
265	public function placeMarkers() {
266		$count = 0;
267		$color = imagecolorallocate ( $this->image, 0, 0, 0 );
268		$bgcolor = imagecolorallocate ( $this->image, 200, 200, 200 );
269		$markerBaseDir = dirname ( __FILE__ ) . '/icons';
270		// loop thru marker array
271		foreach ( $this->markers as $marker ) {
272			// set some local variables
273			$markerLat = $marker ['lat'];
274			$markerLon = $marker ['lon'];
275			$markerType = $marker ['type'];
276			// clear variables from previous loops
277			$markerFilename = '';
278			$markerShadow = '';
279			$matches = false;
280			// check for marker type, get settings from markerPrototypes
281			if ($markerType) {
282				foreach ( $this->markerPrototypes as $markerPrototype ) {
283					if (preg_match ( $markerPrototype ['regex'], $markerType, $matches )) {
284						$markerFilename = $matches [0] . $markerPrototype ['extension'];
285						if ($markerPrototype ['offsetImage']) {
286							list ( $markerImageOffsetX, $markerImageOffsetY ) = explode ( ",", $markerPrototype ['offsetImage'] );
287						}
288						$markerShadow = $markerPrototype ['shadow'];
289						if ($markerShadow) {
290							list ( $markerShadowOffsetX, $markerShadowOffsetY ) = explode ( ",", $markerPrototype ['offsetShadow'] );
291						}
292					}
293				}
294			}
295			// create img resource
296			if (file_exists ( $markerBaseDir . '/' . $markerFilename )) {
297				$markerImg = imagecreatefrompng ( $markerBaseDir . '/' . $markerFilename );
298			} else {
299				$markerImg = imagecreatefrompng ( $markerBaseDir . '/marker.png' );
300			}
301			// check for shadow + create shadow recource
302			if ($markerShadow && file_exists ( $markerBaseDir . '/' . $markerShadow )) {
303				$markerShadowImg = imagecreatefrompng ( $markerBaseDir . '/' . $markerShadow );
304			}
305			// calc position
306			$destX = floor ( ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile ( $markerLon, $this->zoom )) );
307			$destY = floor ( ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile ( $markerLat, $this->zoom )) );
308			// copy shadow on basemap
309			if ($markerShadow && $markerShadowImg) {
310				imagecopy ( $this->image, $markerShadowImg, $destX + intval ( $markerShadowOffsetX ), $destY + intval ( $markerShadowOffsetY ), 0, 0, imagesx ( $markerShadowImg ), imagesy ( $markerShadowImg ) );
311			}
312			// copy marker on basemap above shadow
313			imagecopy ( $this->image, $markerImg, $destX + intval ( $markerImageOffsetX ), $destY + intval ( $markerImageOffsetY ), 0, 0, imagesx ( $markerImg ), imagesy ( $markerImg ) );
314			// add label
315			imagestring ( $this->image, 3, $destX - imagesx ( $markerImg ) + 1, $destY + intval ( $markerImageOffsetY ) + 1, ++ $count, $bgcolor );
316			imagestring ( $this->image, 3, $destX - imagesx ( $markerImg ), $destY + intval ( $markerImageOffsetY ), $count, $color );
317		}
318		;
319	}
320
321	/**
322	 *
323	 * @param string $url
324	 * @return string
325	 */
326	public function tileUrlToFilename($url) {
327		return $this->tileCacheBaseDir . "/" . str_replace ( array (
328				'http://'
329		), '', $url );
330	}
331
332	/**
333	 *
334	 * @param string $url
335	 */
336	public function checkTileCache($url) {
337		$filename = $this->tileUrlToFilename ( $url );
338		if (file_exists ( $filename )) {
339			return file_get_contents ( $filename );
340		}
341	}
342	public function checkMapCache() {
343		$this->mapCacheID = md5 ( $this->serializeParams () );
344		$filename = $this->mapCacheIDToFilename ();
345		if (file_exists ( $filename ))
346			return true;
347	}
348	public function serializeParams() {
349		return join ( "&", array (
350				$this->zoom,
351				$this->lat,
352				$this->lon,
353				$this->width,
354				$this->height,
355				serialize ( $this->markers ),
356				$this->maptype,
357				$this->kmlFileName,
358				$this->gpxFileName,
359				$this->geojsonFileName
360		) );
361	}
362	public function mapCacheIDToFilename() {
363		if (! $this->mapCacheFile) {
364			$this->mapCacheFile = $this->mapCacheBaseDir . "/" . $this->maptype . "/" . $this->zoom . "/cache_" . substr ( $this->mapCacheID, 0, 2 ) . "/" . substr ( $this->mapCacheID, 2, 2 ) . "/" . substr ( $this->mapCacheID, 4 );
365		}
366		return $this->mapCacheFile . "." . $this->mapCacheExtension;
367	}
368
369	/**
370	 * Recursively create the directory.
371	 *
372	 * @param string $pathname
373	 *        	The directory path.
374	 * @param int $mode
375	 *        	File access mode. For more information on modes, read the details on the chmod manpage.
376	 */
377	public function mkdir_recursive($pathname, $mode) {
378		is_dir ( dirname ( $pathname ) ) || $this->mkdir_recursive ( dirname ( $pathname ), $mode );
379		return is_dir ( $pathname ) || @mkdir ( $pathname, $mode );
380	}
381
382	/**
383	 * Write a tile into the cache.
384	 *
385	 * @param string $url
386	 * @param mixed $data
387	 */
388	public function writeTileToCache($url, $data) {
389		$filename = $this->tileUrlToFilename ( $url );
390		$this->mkdir_recursive ( dirname ( $filename ), 0777 );
391		file_put_contents ( $filename, $data );
392	}
393
394	/**
395	 * Fetch a tile and (if configured) store it in the cache.
396	 *
397	 * @param string $url
398	 */
399	public function fetchTile($url) {
400		if ($this->useTileCache && ($cached = $this->checkTileCache ( $url )))
401			return $cached;
402
403		$_UA = 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; ' . PHP_OS . ')';
404		if (function_exists ( "curl_init" )) {
405			// use cUrl
406			$ch = curl_init ();
407			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
408			curl_setopt ( $ch, CURLOPT_USERAGENT, $_UA );
409			curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
410			curl_setopt ( $ch, CURLOPT_URL, $url );
411			$tile = curl_exec ( $ch );
412			curl_close ( $ch );
413		} else {
414			// use file_get_contents
415			global $conf;
416			$opts = array (
417					'http' => array (
418							'method' => "GET",
419							'header' => "Accept-language: en\r\n" . "User-Agent: $_UA\r\n" . "accept: image/png\r\n",
420							'proxy' => "tcp://" . $conf ['proxy'] ['host'] . ":" . $conf ['proxy'] ['port'],
421							'request_fulluri' => true
422					)
423			);
424			$context = stream_context_create ( $opts );
425			$tile = file_get_contents ( $url, false, $context );
426		}
427		if ($tile && $this->useTileCache) {
428			$this->writeTileToCache ( $url, $tile );
429		}
430		return $tile;
431	}
432
433	/**
434	 * Draw gpx trace on the map.
435	 */
436	public function drawGPX() {
437		$col = imagecolorallocatealpha ( $this->image, 0, 0, 255, .4 * 127 );
438		$gpxgeom = geoPHP::load ( file_get_contents ( $this->gpxFileName ), 'gpx' );
439		$this->drawGeometry ( $gpxgeom, $col );
440	}
441
442	/**
443	 * Draw geojson on the map.
444	 */
445	public function drawGeojson() {
446		$col = imagecolorallocatealpha ( $this->image, 255, 0, 255, .4 * 127 );
447		$gpxgeom = geoPHP::load ( file_get_contents ( $this->geojsonFileName ), 'json' );
448		$this->drawGeometry ( $gpxgeom, $col );
449	}
450
451	/**
452	 * Draw kml trace on the map.
453	 */
454	public function drawKML() {
455		// TODO get colour from kml node (not currently supported in geoPHP)
456		$col = imagecolorallocatealpha ( $this->image, 255, 0, 0, .4 * 127 );
457		$kmlgeom = geoPHP::load ( file_get_contents ( $this->kmlFileName ), 'kml' );
458		$this->drawGeometry ( $kmlgeom, $col );
459	}
460
461	/**
462	 * Draw geometry or geometry collection on the map.
463	 *
464	 * @param Geometry $geom
465	 * @param int $colour
466	 *        	drawing colour
467	 */
468	private function drawGeometry($geom, $colour) {
469		switch ($geom->geometryType ()) {
470			case 'GeometryCollection' :
471				// recursively draw part of the collection
472				for($i = 1; $i < $geom->numGeometries () + 1; $i ++) {
473					$_geom = $geom->geometryN ( $i );
474					$this->drawGeometry ( $_geom, $colour );
475				}
476				break;
477			case 'MultiPolygon' :
478				// TODO implement / do nothing
479				break;
480			case 'MultiLineString' :
481				// TODO implement / do nothing
482				break;
483			case 'MultiPoint' :
484				// TODO implement / do nothing
485				break;
486			case 'Polygon' :
487				$this->drawPolygon ( $geom, $colour );
488				break;
489			case 'LineString' :
490				$this->drawLineString ( $geom, $colour );
491				break;
492			case 'Point' :
493				$this->drawPoint ( $geom, $colour );
494				break;
495			default :
496				// draw nothing
497				break;
498		}
499	}
500
501	/**
502	 * Draw a line on the map.
503	 *
504	 * @param LineString $line
505	 * @param int $colour
506	 *        	drawing colour
507	 */
508	private function drawLineString($line, $colour) {
509		imagesetthickness ( $this->image, 2 );
510		for($p = 1; $p < $line->numGeometries (); $p ++) {
511			// get first pair of points
512			$p1 = $line->geometryN ( $p );
513			$p2 = $line->geometryN ( $p + 1 );
514			// translate to paper space
515			$x1 = floor ( ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile ( $p1->x (), $this->zoom )) );
516			$y1 = floor ( ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile ( $p1->y (), $this->zoom )) );
517			$x2 = floor ( ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile ( $p2->x (), $this->zoom )) );
518			$y2 = floor ( ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile ( $p2->y (), $this->zoom )) );
519			// draw to image
520			imageline ( $this->image, $x1, $y1, $x2, $y2, $colour );
521		}
522		imagesetthickness ( $this->image, 1 );
523	}
524
525	/**
526	 * Draw a point on the map.
527	 *
528	 * @param Point $point
529	 * @param int $colour
530	 *        	drawing colour
531	 */
532	private function drawPoint($point, $colour) {
533		imagesetthickness ( $this->image, 2 );
534		// translate to paper space
535		$cx = floor ( ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile ( $point->x (), $this->zoom )) );
536		$cy = floor ( ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile ( $point->y (), $this->zoom )) );
537		$r = 5;
538		// draw to image
539		// imageellipse($this->image, $cx, $cy,$r, $r, $colour);
540		imagefilledellipse ( $this->image, $cx, $cy, $r, $r, $colour );
541		// don't use imageellipse because the imagesetthickness function has
542		// no effect. So the better workaround is to use imagearc.
543		imagearc ( $this->image, $cx, $cy, $r, $r, 0, 359, $colour );
544		imagesetthickness ( $this->image, 1 );
545	}
546
547	/**
548	 * Draw a polygon on the map.
549	 *
550	 * @param Polygon $polygon
551	 * @param int $colour
552	 *        	drawing colour
553	 */
554	private function drawPolygon($polygon, $colour) {
555		// TODO implementation of drawing holes,
556		// maybe draw the polygon to an in-memory image and use imagecopy, draw polygon in col., draw holes in bgcol?
557
558		// print_r('Polygon:<br />');
559		// print_r($polygon);
560		$extPoints = array ();
561		// extring is a linestring actually..
562		$extRing = $polygon->exteriorRing ();
563
564		for($i = 1; $i < $extRing->numGeometries (); $i ++) {
565			$p1 = $extRing->geometryN ( $i );
566			$x = floor ( ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile ( $p1->x (), $this->zoom )) );
567			$y = floor ( ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile ( $p1->y (), $this->zoom )) );
568			$extPoints [] = $x;
569			$extPoints [] = $y;
570		}
571		// print_r('points:('.($i-1).')<br />');
572		// print_r($extPoints);
573		// imagepolygon ($this->image, $extPoints, $i-1, $colour );
574		imagefilledpolygon ( $this->image, $extPoints, $i - 1, $colour );
575	}
576
577	/**
578	 * add copyright and origin notice and icons to the map.
579	 */
580	public function drawCopyright() {
581		$logoBaseDir = dirname ( __FILE__ ) . '/' . 'logo/';
582		$logoImg = imagecreatefrompng ( $logoBaseDir . $this->tileInfo ['openstreetmap'] ['logo'] );
583		$textcolor = imagecolorallocate ( $this->image, 0, 0, 0 );
584		$bgcolor = imagecolorallocate ( $this->image, 200, 200, 200 );
585
586		imagecopy ( $this->image, $logoImg, 0, imagesy ( $this->image ) - imagesy ( $logoImg ), 0, 0, imagesx ( $logoImg ), imagesy ( $logoImg ) );
587		imagestring ( $this->image, 1, imagesx ( $logoImg ) + 2, imagesy ( $this->image ) - imagesy ( $logoImg ) + 1, $this->tileInfo ['openstreetmap'] ['txt'], $bgcolor );
588		imagestring ( $this->image, 1, imagesx ( $logoImg ) + 1, imagesy ( $this->image ) - imagesy ( $logoImg ), $this->tileInfo ['openstreetmap'] ['txt'], $textcolor );
589
590		// additional tile source info, ie. who created/hosted the tiles
591		if ($this->maptype != 'openstreetmap') {
592			$iconImg = imagecreatefrompng ( $logoBaseDir . $this->tileInfo [$this->maptype] ['logo'] );
593			imagecopy ( $this->image, $iconImg, imagesx ( $logoImg ) + 1, imagesy ( $this->image ) - imagesy ( $iconImg ), 0, 0, imagesx ( $iconImg ), imagesy ( $iconImg ) );
594			imagestring ( $this->image, 1, imagesx ( $logoImg ) + imagesx ( $iconImg ) + 4, imagesy ( $this->image ) - ceil ( imagesy ( $logoImg ) / 2 ) + 1, $this->tileInfo [$this->maptype] ['txt'], $bgcolor );
595			imagestring ( $this->image, 1, imagesx ( $logoImg ) + imagesx ( $iconImg ) + 3, imagesy ( $this->image ) - ceil ( imagesy ( $logoImg ) / 2 ), $this->tileInfo [$this->maptype] ['txt'], $textcolor );
596		}
597	}
598
599	/**
600	 * make the map.
601	 */
602	public function makeMap() {
603		$this->initCoords ();
604		$this->createBaseMap ();
605		if (! empty ( $this->markers ))
606			$this->placeMarkers ();
607		if (file_exists ( $this->kmlFileName ))
608			$this->drawKML ();
609		if (file_exists ( $this->gpxFileName ))
610			$this->drawGPX ();
611		if (file_exists ( $this->geojsonFileName ))
612			$this->drawGeojson ();
613
614		$this->drawCopyright ();
615	}
616
617	/**
618	 * Calculate the lat/lon/zoom values to make sure that all of the markers and gpx/kml are on the map.
619	 * can throw an error like
620	 * "Fatal error: Uncaught Exception: Cannot create a collection with non-geometries in
621	 * D:\www\wild-water.nl\www\dokuwiki\lib\plugins\geophp\geoPHP\lib\geometry\Collection.class.php:29"
622	 *
623	 * @param float $paddingFactor
624	 *        	buffer constant to enlarge (>1.0) the zoom level
625	 */
626	private function autoZoom($paddingFactor = 1.0) {
627		$geoms = array ();
628		$geoms [] = new Point ( $this->lon, $this->lat );
629		if (! empty ( $this->markers )) {
630			foreach ( $this->markers as $marker ) {
631				$geoms [] = new Point ( $marker ['lon'], $marker ['lat'] );
632			}
633		}
634		$g = FALSE;
635		if (file_exists ( $this->kmlFileName )) {
636			$g = geoPHP::load ( file_get_contents ( $this->kmlFileName ), 'kml' );
637			if($g !== FALSE) {
638				$geoms [] = $g;
639			}
640		}
641		if (file_exists ( $this->gpxFileName )) {
642			$g = geoPHP::load ( file_get_contents ( $this->gpxFileName ), 'gpx' );
643			if($g !== FALSE) {
644				$geoms [] = $g;
645			}
646		}
647		if (file_exists ( $this->geojsonFileName )) {
648			$g = geoPHP::load ( file_get_contents ( $this->geojsonFileName ), 'geojson' );
649			if($g !== FALSE) {
650				$geoms [] = $g;
651			}
652		}
653
654		if (count ( $geoms ) <= 1) {
655			dbglog($geoms,"StaticMap::autoZoom: Skip setting autozoom options");
656			return;
657		}
658
659		$geom = new GeometryCollection ( $geoms );
660		$centroid = $geom->centroid ();
661		$bbox = $geom->getBBox ();
662
663		// determine vertical resolution, this depends on the distance from the equator
664		// $vy00 = log(tan(M_PI*(0.25 + $centroid->getY()/360)));
665		$vy0 = log ( tan ( M_PI * (0.25 + $bbox ['miny'] / 360) ) );
666		$vy1 = log ( tan ( M_PI * (0.25 + $bbox ['maxy'] / 360) ) );
667		dbglog("StaticMap::autoZoom: vertical resolution: $vy0, $vy1");
668		$zoomFactorPowered = ($this->height / 2) / (40.7436654315252 * ($vy1 - $vy0));
669		$resolutionVertical = 360 / ($zoomFactorPowered * $this->tileSize);
670		// determine horizontal resolution
671		$resolutionHorizontal = ($bbox ['maxx'] - $bbox ['minx']) / $this->width;
672		$resolution = max ( $resolutionHorizontal, $resolutionVertical ) * $paddingFactor;
673		$zoom = log ( 360 / ($resolution * $this->tileSize), 2 );
674
675		if (is_finite($zoom) && $zoom < 15 && $zoom > 2) {
676			$this->zoom = floor ( $zoom );
677		}
678		$this->lon = $centroid->getX ();
679		$this->lat = $centroid->getY ();
680		dbglog("StaticMap::autoZoom: Set autozoom options to: z: $this->zoom, lon: $this->lon, lat: $this->lat");
681	}
682
683	/**
684	 * get the map, this may return a reference to a cached copy.
685	 *
686	 * @return string url relative to media dir
687	 */
688	public function getMap() {
689		try {
690			if ($this->autoZoomExtent) {
691				$this->autoZoom ();
692			}
693		} catch (Exception $e) {
694			dbglog($e);
695		}
696
697			// use map cache, so check cache for map
698		if (! $this->checkMapCache ()) {
699			// map is not in cache, needs to be build
700			$this->makeMap ();
701			$this->mkdir_recursive ( dirname ( $this->mapCacheIDToFilename () ), 0777 );
702			imagepng ( $this->image, $this->mapCacheIDToFilename (), 9 );
703		}
704		$this->doc = $this->mapCacheIDToFilename ();
705		// make url relative to media dir
706		return str_replace ( $this->mediaBaseDir, '', $this->doc );
707	}
708}
709