xref: /plugin/openlayersmap/StaticMap.php (revision ab8cbd2baf29a832ccd9d40f1734e2ba1f0d0649)
1628e43ccSMark Prins<?php
2628e43ccSMark Prins/*
3d768c538SMark Prins * Copyright (c) 2012-2014 Mark C. Prins <mprins@users.sf.net>
4628e43ccSMark Prins *
5f4b9bdacSMark Prins * In part based on staticMapLite 0.03 available at http://staticmaplite.svn.sourceforge.net/viewvc/staticmaplite/
6628e43ccSMark Prins *
7628e43ccSMark Prins * Copyright (c) 2009 Gerhard Koch <gerhard.koch AT ymail.com>
8628e43ccSMark Prins *
9628e43ccSMark Prins * Licensed under the Apache License, Version 2.0 (the "License");
10628e43ccSMark Prins * you may not use this file except in compliance with the License.
11628e43ccSMark Prins * You may obtain a copy of the License at
12628e43ccSMark Prins *
13628e43ccSMark Prins *     http://www.apache.org/licenses/LICENSE-2.0
14628e43ccSMark Prins *
15628e43ccSMark Prins * Unless required by applicable law or agreed to in writing, software
16628e43ccSMark Prins * distributed under the License is distributed on an "AS IS" BASIS,
17628e43ccSMark Prins * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18628e43ccSMark Prins * See the License for the specific language governing permissions and
19628e43ccSMark Prins * limitations under the License.
20628e43ccSMark Prins */
21f4b9bdacSMark Prinsinclude_once (realpath ( dirname ( __FILE__ ) ) . '/../geophp/geoPHP/geoPHP.inc');
22628e43ccSMark Prins/**
23*ab8cbd2bSMark Prins *
24628e43ccSMark Prins * @author Mark C. Prins <mprins@users.sf.net>
25628e43ccSMark Prins * @author Gerhard Koch <gerhard.koch AT ymail.com>
26628e43ccSMark Prins *
27628e43ccSMark Prins */
28628e43ccSMark Prinsclass StaticMap {
29*ab8cbd2bSMark Prins	// this should probably not be changed
30628e43ccSMark Prins	protected $tileSize = 256;
31628e43ccSMark Prins
32628e43ccSMark Prins	// the final output
33628e43ccSMark Prins	var $doc = '';
34628e43ccSMark Prins
35628e43ccSMark Prins	protected $tileInfo = array (
36628e43ccSMark Prins			// OSM sources
37628e43ccSMark Prins			'openstreetmap' => array (
38628e43ccSMark Prins					'txt' => '(c) OpenStreetMap CC-BY-SA',
39628e43ccSMark Prins					'logo' => 'osm_logo.png',
40*ab8cbd2bSMark Prins					'url' => 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'
41*ab8cbd2bSMark Prins			),
42628e43ccSMark Prins			// OCM sources
43628e43ccSMark Prins			'cycle' => array (
44628e43ccSMark Prins					'txt' => 'OpenCycleMap tiles',
45628e43ccSMark Prins					'logo' => 'cycle_logo.png',
46*ab8cbd2bSMark Prins					'url' => 'http://tile.opencyclemap.org/cycle/{Z}/{X}/{Y}.png'
47*ab8cbd2bSMark Prins			),
48628e43ccSMark Prins			'transport' => array (
49628e43ccSMark Prins					'txt' => 'OpenCycleMap tiles',
50628e43ccSMark Prins					'logo' => 'cycle_logo.png',
51*ab8cbd2bSMark Prins					'url' => 'http://tile2.opencyclemap.org/transport/{Z}/{X}/{Y}.png'
52*ab8cbd2bSMark Prins			),
53628e43ccSMark Prins			'landscape' => array (
54628e43ccSMark Prins					'txt' => 'OpenCycleMap tiles',
55628e43ccSMark Prins					'logo' => 'cycle_logo.png',
56*ab8cbd2bSMark Prins					'url' => 'http://tile3.opencyclemap.org/landscape/{Z}/{X}/{Y}.png'
57*ab8cbd2bSMark Prins			),
58628e43ccSMark Prins			// H&B sources
59628e43ccSMark Prins			'hikeandbike' => array (
60628e43ccSMark Prins					'txt' => 'Hike & Bike Map',
61628e43ccSMark Prins					'logo' => 'hnb_logo.png',
62*ab8cbd2bSMark Prins					'url' => 'http://toolserver.org/tiles/hikebike/{Z}/{X}/{Y}.png'
63*ab8cbd2bSMark Prins			),
64628e43ccSMark Prins			// 'piste'=>array(
65628e43ccSMark Prins			// 'txt'=>'OpenPisteMap tiles',
66628e43ccSMark Prins			// 'logo'=>'piste_logo.png',
67628e43ccSMark Prins			// 'url'=>''),
68628e43ccSMark Prins			// 'sea'=>array(
69628e43ccSMark Prins			// 'txt'=>'OpenSeaMap tiles',
70628e43ccSMark Prins			// 'logo'=>'sea_logo.png',
71628e43ccSMark Prins			// 'url'=>''),
72628e43ccSMark Prins			// MapQuest
73628e43ccSMark Prins			'mapquest' => array (
74628e43ccSMark Prins					'txt' => 'MapQuest tiles',
75628e43ccSMark Prins					'logo' => 'mq_logo.png',
76*ab8cbd2bSMark Prins					'url' => 'http://otile3.mqcdn.com/tiles/1.0.0/map/{Z}/{X}/{Y}.png'
77*ab8cbd2bSMark Prins			)
78628e43ccSMark Prins	);
79628e43ccSMark Prins	protected $tileDefaultSrc = 'openstreetmap';
80628e43ccSMark Prins
81628e43ccSMark Prins	// set up markers
82628e43ccSMark Prins	protected $markerPrototypes = array (
83628e43ccSMark Prins			// found at http://www.mapito.net/map-marker-icons.html
84628e43ccSMark Prins			// these are 17x19 px with a pointer at the bottom left
85*ab8cbd2bSMark Prins			'lightblue' => array (
86*ab8cbd2bSMark Prins					'regex' => '/^lightblue([0-9]+)$/',
87628e43ccSMark Prins					'extension' => '.png',
88628e43ccSMark Prins					'shadow' => false,
89628e43ccSMark Prins					'offsetImage' => '0,-19',
90628e43ccSMark Prins					'offsetShadow' => false
91628e43ccSMark Prins			),
92628e43ccSMark Prins			// openlayers std markers are 21x25px with shadow
93*ab8cbd2bSMark Prins			'ol-marker' => array (
94*ab8cbd2bSMark Prins					'regex' => '/^marker(|-blue|-gold|-green|-red)+$/',
95628e43ccSMark Prins					'extension' => '.png',
96628e43ccSMark Prins					'shadow' => 'marker_shadow.png',
97628e43ccSMark Prins					'offsetImage' => '-10,-25',
98628e43ccSMark Prins					'offsetShadow' => '-1,-13'
99628e43ccSMark Prins			),
100628e43ccSMark Prins			// these are 16x16 px
101*ab8cbd2bSMark Prins			'ww_icon' => array (
102*ab8cbd2bSMark Prins					'regex' => '/ww_\S+$/',
103628e43ccSMark Prins					'extension' => '.png',
104628e43ccSMark Prins					'shadow' => false,
105628e43ccSMark Prins					'offsetImage' => '-8,-8',
106628e43ccSMark Prins					'offsetShadow' => false
107628e43ccSMark Prins			),
108628e43ccSMark Prins			// assume these are 16x16 px
109*ab8cbd2bSMark Prins			'rest' => array (
110*ab8cbd2bSMark Prins					'regex' => '/^(?!lightblue([0-9]+)$)(?!(ww_\S+$))(?!marker(|-blue|-gold|-green|-red)+$)(.*)/',
111628e43ccSMark Prins					'extension' => '.png',
112628e43ccSMark Prins					'shadow' => 'marker_shadow.png',
113628e43ccSMark Prins					'offsetImage' => '-8,-8',
114628e43ccSMark Prins					'offsetShadow' => '-1,-1'
115628e43ccSMark Prins			)
116628e43ccSMark Prins	);
117628e43ccSMark Prins	protected $centerX, $centerY, $offsetX, $offsetY, $image;
1186914b920SMark Prins	protected $zoom, $lat, $lon, $width, $height, $markers, $maptype, $kmlFileName, $gpxFileName, $geojsonFileName, $autoZoomExtent;
119628e43ccSMark Prins	protected $tileCacheBaseDir, $mapCacheBaseDir, $mediaBaseDir;
120628e43ccSMark Prins	protected $useTileCache = true;
121628e43ccSMark Prins	protected $mapCacheID = '';
122628e43ccSMark Prins	protected $mapCacheFile = '';
123628e43ccSMark Prins	protected $mapCacheExtension = 'png';
124628e43ccSMark Prins
125628e43ccSMark Prins	/**
126f4b9bdacSMark Prins	 * Constructor.
127*ab8cbd2bSMark Prins	 *
128*ab8cbd2bSMark Prins	 * @param float $lat
129*ab8cbd2bSMark Prins	 *        	Latitude (x) of center of map
130*ab8cbd2bSMark Prins	 * @param float $lon
131*ab8cbd2bSMark Prins	 *        	Longitude (y) of center of map
132*ab8cbd2bSMark Prins	 * @param int $zoom
133*ab8cbd2bSMark Prins	 *        	Zoomlevel
134*ab8cbd2bSMark Prins	 * @param int $width
135*ab8cbd2bSMark Prins	 *        	Width in pixels
136*ab8cbd2bSMark Prins	 * @param int $height
137*ab8cbd2bSMark Prins	 *        	Height in pixels
138*ab8cbd2bSMark Prins	 * @param string $maptype
139*ab8cbd2bSMark Prins	 *        	Name of the map
140*ab8cbd2bSMark Prins	 * @param mixed $markers
141*ab8cbd2bSMark Prins	 *        	array of markers
142*ab8cbd2bSMark Prins	 * @param string $gpx
143*ab8cbd2bSMark Prins	 *        	GPX filename
144*ab8cbd2bSMark Prins	 * @param string $kml
145*ab8cbd2bSMark Prins	 *        	KML filename
146*ab8cbd2bSMark Prins	 * @param string $mediaDir
147*ab8cbd2bSMark Prins	 *        	Directory to store/cache maps
148*ab8cbd2bSMark Prins	 * @param string $tileCacheBaseDir
149*ab8cbd2bSMark Prins	 *        	Directory to cache map tiles
150*ab8cbd2bSMark Prins	 * @param boolean $autoZoomExtent
151*ab8cbd2bSMark Prins	 *        	Wheter or not to override zoom/lat/lon and zoom to the extent of gpx/kml and markers
152628e43ccSMark Prins	 */
1536914b920SMark Prins	public function __construct($lat, $lon, $zoom, $width, $height, $maptype, $markers, $gpx, $kml, $geojson, $mediaDir, $tileCacheBaseDir, $autoZoomExtent = TRUE) {
154628e43ccSMark Prins		$this->zoom = $zoom;
155628e43ccSMark Prins		$this->lat = $lat;
156628e43ccSMark Prins		$this->lon = $lon;
157628e43ccSMark Prins		$this->width = $width;
158628e43ccSMark Prins		$this->height = $height;
159628e43ccSMark Prins		// validate + set maptype
160628e43ccSMark Prins		$this->maptype = $this->tileDefaultSrc;
161628e43ccSMark Prins		if (array_key_exists ( $maptype, $this->tileInfo )) {
162628e43ccSMark Prins			$this->maptype = $maptype;
163628e43ccSMark Prins		}
1642d11d700SMark Prins		$this->markers = $markers;
1652d11d700SMark Prins		$this->kmlFileName = $kml;
1662d11d700SMark Prins		$this->gpxFileName = $gpx;
1676914b920SMark Prins		$this->geojsonFileName = $geojson;
1682d11d700SMark Prins		$this->mediaBaseDir = $mediaDir;
169628e43ccSMark Prins		$this->tileCacheBaseDir = $tileCacheBaseDir . '/olmaptiles';
170628e43ccSMark Prins		$this->useTileCache = $this->tileCacheBaseDir !== '';
171628e43ccSMark Prins		$this->mapCacheBaseDir = $mediaDir . '/olmapmaps';
1722d11d700SMark Prins		$this->autoZoomExtent = $autoZoomExtent;
173628e43ccSMark Prins	}
174628e43ccSMark Prins
175628e43ccSMark Prins	/**
176628e43ccSMark Prins	 *
177628e43ccSMark Prins	 * @param number $long
178628e43ccSMark Prins	 * @param number $zoom
179f4b9bdacSMark Prins	 * @return number
180628e43ccSMark Prins	 */
181628e43ccSMark Prins	public function lonToTile($long, $zoom) {
182628e43ccSMark Prins		return (($long + 180) / 360) * pow ( 2, $zoom );
183628e43ccSMark Prins	}
184628e43ccSMark Prins	/**
185628e43ccSMark Prins	 *
186628e43ccSMark Prins	 * @param number $lat
187628e43ccSMark Prins	 * @param number $zoom
188628e43ccSMark Prins	 * @return number
189628e43ccSMark Prins	 */
190628e43ccSMark Prins	public function latToTile($lat, $zoom) {
1912d11d700SMark Prins		return (1 - log ( tan ( $lat * pi () / 180 ) + 1 / cos ( $lat * M_PI / 180 ) ) / M_PI) / 2 * pow ( 2, $zoom );
192628e43ccSMark Prins	}
193f4b9bdacSMark Prins
194628e43ccSMark Prins	/**
195628e43ccSMark Prins	 */
196628e43ccSMark Prins	public function initCoords() {
197628e43ccSMark Prins		$this->centerX = $this->lonToTile ( $this->lon, $this->zoom );
198628e43ccSMark Prins		$this->centerY = $this->latToTile ( $this->lat, $this->zoom );
199628e43ccSMark Prins		$this->offsetX = floor ( (floor ( $this->centerX ) - $this->centerX) * $this->tileSize );
200628e43ccSMark Prins		$this->offsetY = floor ( (floor ( $this->centerY ) - $this->centerY) * $this->tileSize );
201628e43ccSMark Prins	}
202628e43ccSMark Prins
203628e43ccSMark Prins	/**
204628e43ccSMark Prins	 * make basemap image.
205628e43ccSMark Prins	 */
206628e43ccSMark Prins	public function createBaseMap() {
207628e43ccSMark Prins		$this->image = imagecreatetruecolor ( $this->width, $this->height );
208628e43ccSMark Prins		$startX = floor ( $this->centerX - ($this->width / $this->tileSize) / 2 );
209628e43ccSMark Prins		$startY = floor ( $this->centerY - ($this->height / $this->tileSize) / 2 );
210628e43ccSMark Prins		$endX = ceil ( $this->centerX + ($this->width / $this->tileSize) / 2 );
211628e43ccSMark Prins		$endY = ceil ( $this->centerY + ($this->height / $this->tileSize) / 2 );
212628e43ccSMark Prins		$this->offsetX = - floor ( ($this->centerX - floor ( $this->centerX )) * $this->tileSize );
213628e43ccSMark Prins		$this->offsetY = - floor ( ($this->centerY - floor ( $this->centerY )) * $this->tileSize );
214628e43ccSMark Prins		$this->offsetX += floor ( $this->width / 2 );
215628e43ccSMark Prins		$this->offsetY += floor ( $this->height / 2 );
216628e43ccSMark Prins		$this->offsetX += floor ( $startX - floor ( $this->centerX ) ) * $this->tileSize;
217628e43ccSMark Prins		$this->offsetY += floor ( $startY - floor ( $this->centerY ) ) * $this->tileSize;
218628e43ccSMark Prins
219628e43ccSMark Prins		for($x = $startX; $x <= $endX; $x ++) {
220628e43ccSMark Prins			for($y = $startY; $y <= $endY; $y ++) {
221*ab8cbd2bSMark Prins				$url = str_replace ( array (
222*ab8cbd2bSMark Prins						'{Z}',
223*ab8cbd2bSMark Prins						'{X}',
224*ab8cbd2bSMark Prins						'{Y}'
225*ab8cbd2bSMark Prins				), array (
226*ab8cbd2bSMark Prins						$this->zoom,
227*ab8cbd2bSMark Prins						$x,
228*ab8cbd2bSMark Prins						$y
229*ab8cbd2bSMark Prins				), $this->tileInfo [$this->maptype] ['url'] );
230628e43ccSMark Prins				$tileData = $this->fetchTile ( $url );
231628e43ccSMark Prins				if ($tileData) {
232628e43ccSMark Prins					$tileImage = imagecreatefromstring ( $tileData );
233628e43ccSMark Prins				} else {
234628e43ccSMark Prins					$tileImage = imagecreate ( $this->tileSize, $this->tileSize );
235628e43ccSMark Prins					$color = imagecolorallocate ( $tileImage, 255, 255, 255 );
236628e43ccSMark Prins					@imagestring ( $tileImage, 1, 127, 127, 'err', $color );
237628e43ccSMark Prins				}
238628e43ccSMark Prins				$destX = ($x - $startX) * $this->tileSize + $this->offsetX;
239628e43ccSMark Prins				$destY = ($y - $startY) * $this->tileSize + $this->offsetY;
240628e43ccSMark Prins				imagecopy ( $this->image, $tileImage, $destX, $destY, 0, 0, $this->tileSize, $this->tileSize );
241628e43ccSMark Prins			}
242628e43ccSMark Prins		}
243628e43ccSMark Prins	}
244628e43ccSMark Prins
245628e43ccSMark Prins	/**
246628e43ccSMark Prins	 * Place markers on the map and number them in the same order as they are listed in the html.
247628e43ccSMark Prins	 */
248628e43ccSMark Prins	public function placeMarkers() {
249628e43ccSMark Prins		$count = 0;
250628e43ccSMark Prins		$color = imagecolorallocate ( $this->image, 0, 0, 0 );
251628e43ccSMark Prins		$bgcolor = imagecolorallocate ( $this->image, 200, 200, 200 );
252628e43ccSMark Prins		$markerBaseDir = dirname ( __FILE__ ) . '/icons';
253628e43ccSMark Prins		// loop thru marker array
254628e43ccSMark Prins		foreach ( $this->markers as $marker ) {
255628e43ccSMark Prins			// set some local variables
256628e43ccSMark Prins			$markerLat = $marker ['lat'];
257628e43ccSMark Prins			$markerLon = $marker ['lon'];
258628e43ccSMark Prins			$markerType = $marker ['type'];
259628e43ccSMark Prins			// clear variables from previous loops
260628e43ccSMark Prins			$markerFilename = '';
261628e43ccSMark Prins			$markerShadow = '';
262628e43ccSMark Prins			$matches = false;
263628e43ccSMark Prins			// check for marker type, get settings from markerPrototypes
264628e43ccSMark Prins			if ($markerType) {
265628e43ccSMark Prins				foreach ( $this->markerPrototypes as $markerPrototype ) {
266628e43ccSMark Prins					if (preg_match ( $markerPrototype ['regex'], $markerType, $matches )) {
267628e43ccSMark Prins						$markerFilename = $matches [0] . $markerPrototype ['extension'];
268628e43ccSMark Prins						if ($markerPrototype ['offsetImage']) {
269628e43ccSMark Prins							list ( $markerImageOffsetX, $markerImageOffsetY ) = split ( ",", $markerPrototype ['offsetImage'] );
270628e43ccSMark Prins						}
271628e43ccSMark Prins						$markerShadow = $markerPrototype ['shadow'];
272628e43ccSMark Prins						if ($markerShadow) {
273628e43ccSMark Prins							list ( $markerShadowOffsetX, $markerShadowOffsetY ) = split ( ",", $markerPrototype ['offsetShadow'] );
274628e43ccSMark Prins						}
275628e43ccSMark Prins					}
276628e43ccSMark Prins				}
277628e43ccSMark Prins			}
278628e43ccSMark Prins			// create img resource
279628e43ccSMark Prins			if (file_exists ( $markerBaseDir . '/' . $markerFilename )) {
280628e43ccSMark Prins				$markerImg = imagecreatefrompng ( $markerBaseDir . '/' . $markerFilename );
281628e43ccSMark Prins			} else {
282628e43ccSMark Prins				$markerImg = imagecreatefrompng ( $markerBaseDir . '/marker.png' );
283628e43ccSMark Prins			}
284628e43ccSMark Prins			// check for shadow + create shadow recource
285628e43ccSMark Prins			if ($markerShadow && file_exists ( $markerBaseDir . '/' . $markerShadow )) {
286628e43ccSMark Prins				$markerShadowImg = imagecreatefrompng ( $markerBaseDir . '/' . $markerShadow );
287628e43ccSMark Prins			}
288628e43ccSMark Prins			// calc position
289628e43ccSMark Prins			$destX = floor ( ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile ( $markerLon, $this->zoom )) );
290628e43ccSMark Prins			$destY = floor ( ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile ( $markerLat, $this->zoom )) );
291628e43ccSMark Prins			// copy shadow on basemap
292628e43ccSMark Prins			if ($markerShadow && $markerShadowImg) {
293*ab8cbd2bSMark Prins				imagecopy ( $this->image, $markerShadowImg, $destX + intval ( $markerShadowOffsetX ), $destY + intval ( $markerShadowOffsetY ), 0, 0, imagesx ( $markerShadowImg ), imagesy ( $markerShadowImg ) );
294628e43ccSMark Prins			}
295628e43ccSMark Prins			// copy marker on basemap above shadow
296*ab8cbd2bSMark Prins			imagecopy ( $this->image, $markerImg, $destX + intval ( $markerImageOffsetX ), $destY + intval ( $markerImageOffsetY ), 0, 0, imagesx ( $markerImg ), imagesy ( $markerImg ) );
297628e43ccSMark Prins			// add label
298628e43ccSMark Prins			imagestring ( $this->image, 3, $destX - imagesx ( $markerImg ) + 1, $destY + intval ( $markerImageOffsetY ) + 1, ++ $count, $bgcolor );
299628e43ccSMark Prins			imagestring ( $this->image, 3, $destX - imagesx ( $markerImg ), $destY + intval ( $markerImageOffsetY ), $count, $color );
300*ab8cbd2bSMark Prins		}
301*ab8cbd2bSMark Prins		;
302628e43ccSMark Prins	}
30357e65445SMark Prins
304628e43ccSMark Prins	/**
305628e43ccSMark Prins	 *
306628e43ccSMark Prins	 * @param string $url
307628e43ccSMark Prins	 * @return string
308628e43ccSMark Prins	 */
309628e43ccSMark Prins	public function tileUrlToFilename($url) {
310*ab8cbd2bSMark Prins		return $this->tileCacheBaseDir . "/" . str_replace ( array (
311*ab8cbd2bSMark Prins				'http://'
312*ab8cbd2bSMark Prins		), '', $url );
313628e43ccSMark Prins	}
31457e65445SMark Prins
315628e43ccSMark Prins	/**
316628e43ccSMark Prins	 *
317628e43ccSMark Prins	 * @param string $url
318628e43ccSMark Prins	 */
319628e43ccSMark Prins	public function checkTileCache($url) {
320628e43ccSMark Prins		$filename = $this->tileUrlToFilename ( $url );
321628e43ccSMark Prins		if (file_exists ( $filename )) {
322628e43ccSMark Prins			return file_get_contents ( $filename );
323628e43ccSMark Prins		}
324628e43ccSMark Prins	}
325628e43ccSMark Prins	public function checkMapCache() {
326628e43ccSMark Prins		$this->mapCacheID = md5 ( $this->serializeParams () );
327628e43ccSMark Prins		$filename = $this->mapCacheIDToFilename ();
328*ab8cbd2bSMark Prins		if (file_exists ( $filename ))
329*ab8cbd2bSMark Prins			return true;
330628e43ccSMark Prins	}
331628e43ccSMark Prins	public function serializeParams() {
332*ab8cbd2bSMark Prins		return join ( "&", array (
333*ab8cbd2bSMark Prins				$this->zoom,
334*ab8cbd2bSMark Prins				$this->lat,
335*ab8cbd2bSMark Prins				$this->lon,
336*ab8cbd2bSMark Prins				$this->width,
337*ab8cbd2bSMark Prins				$this->height,
338*ab8cbd2bSMark Prins				serialize ( $this->markers ),
339*ab8cbd2bSMark Prins				$this->maptype,
340*ab8cbd2bSMark Prins				$this->kmlFileName,
341*ab8cbd2bSMark Prins				$this->gpxFileName,
342*ab8cbd2bSMark Prins				$this->geojsonFileName
343*ab8cbd2bSMark Prins		) );
344628e43ccSMark Prins	}
345628e43ccSMark Prins	public function mapCacheIDToFilename() {
346628e43ccSMark Prins		if (! $this->mapCacheFile) {
347628e43ccSMark Prins			$this->mapCacheFile = $this->mapCacheBaseDir . "/" . $this->maptype . "/" . $this->zoom . "/cache_" . substr ( $this->mapCacheID, 0, 2 ) . "/" . substr ( $this->mapCacheID, 2, 2 ) . "/" . substr ( $this->mapCacheID, 4 );
348628e43ccSMark Prins		}
349628e43ccSMark Prins		return $this->mapCacheFile . "." . $this->mapCacheExtension;
350628e43ccSMark Prins	}
35157e65445SMark Prins
3522d11d700SMark Prins	/**
3532d11d700SMark Prins	 * Recursively create the directory.
354*ab8cbd2bSMark Prins	 *
355*ab8cbd2bSMark Prins	 * @param string $pathname
356*ab8cbd2bSMark Prins	 *        	The directory path.
357*ab8cbd2bSMark Prins	 * @param int $mode
358*ab8cbd2bSMark Prins	 *        	File access mode. For more information on modes, read the details on the chmod manpage.
3592d11d700SMark Prins	 */
360628e43ccSMark Prins	public function mkdir_recursive($pathname, $mode) {
361628e43ccSMark Prins		is_dir ( dirname ( $pathname ) ) || $this->mkdir_recursive ( dirname ( $pathname ), $mode );
362628e43ccSMark Prins		return is_dir ( $pathname ) || @mkdir ( $pathname, $mode );
363628e43ccSMark Prins	}
364628e43ccSMark Prins
3652d11d700SMark Prins	/**
3662d11d700SMark Prins	 * Write a tile into the cache.
367*ab8cbd2bSMark Prins	 *
3682d11d700SMark Prins	 * @param string $url
3692d11d700SMark Prins	 * @param mixed $data
3702d11d700SMark Prins	 */
371628e43ccSMark Prins	public function writeTileToCache($url, $data) {
372628e43ccSMark Prins		$filename = $this->tileUrlToFilename ( $url );
373628e43ccSMark Prins		$this->mkdir_recursive ( dirname ( $filename ), 0777 );
374628e43ccSMark Prins		file_put_contents ( $filename, $data );
375628e43ccSMark Prins	}
37657e65445SMark Prins
3772d11d700SMark Prins	/**
3782d11d700SMark Prins	 * Fetch a tile and (if configured) store it in the cache.
379*ab8cbd2bSMark Prins	 *
3802d11d700SMark Prins	 * @param string $url
3812d11d700SMark Prins	 */
382628e43ccSMark Prins	public function fetchTile($url) {
383*ab8cbd2bSMark Prins		if ($this->useTileCache && ($cached = $this->checkTileCache ( $url )))
384*ab8cbd2bSMark Prins			return $cached;
385e4f115f4SMark Prins
386e4f115f4SMark Prins		$_UA = 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; ' . PHP_OS . ')';
387e4f115f4SMark Prins		if (function_exists ( "curl_init" )) {
388e4f115f4SMark Prins			// use cUrl
389628e43ccSMark Prins			$ch = curl_init ();
390628e43ccSMark Prins			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
391e4f115f4SMark Prins			curl_setopt ( $ch, CURLOPT_USERAGENT, $_UA );
392628e43ccSMark Prins			curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
393628e43ccSMark Prins			curl_setopt ( $ch, CURLOPT_URL, $url );
394628e43ccSMark Prins			$tile = curl_exec ( $ch );
395628e43ccSMark Prins			curl_close ( $ch );
396e4f115f4SMark Prins		} else {
397e4f115f4SMark Prins			// use file_get_contents
398e4f115f4SMark Prins			global $conf;
399e4f115f4SMark Prins			$opts = array (
400e4f115f4SMark Prins					'http' => array (
401e4f115f4SMark Prins							'method' => "GET",
402*ab8cbd2bSMark Prins							'header' => "Accept-language: en\r\n" . "User-Agent: $_UA\r\n" . "accept: image/png\r\n",
403e4f115f4SMark Prins							'proxy' => "tcp://" . $conf ['proxy'] ['host'] . ":" . $conf ['proxy'] ['port'],
404*ab8cbd2bSMark Prins							'request_fulluri' => true
405e4f115f4SMark Prins					)
406e4f115f4SMark Prins			);
407e4f115f4SMark Prins			$context = stream_context_create ( $opts );
408e4f115f4SMark Prins			$tile = file_get_contents ( $url, false, $context );
409e4f115f4SMark Prins		}
410628e43ccSMark Prins		if ($tile && $this->useTileCache) {
411628e43ccSMark Prins			$this->writeTileToCache ( $url, $tile );
412628e43ccSMark Prins		}
413628e43ccSMark Prins		return $tile;
414628e43ccSMark Prins	}
415628e43ccSMark Prins
416628e43ccSMark Prins	/**
417628e43ccSMark Prins	 * Draw gpx trace on the map.
418628e43ccSMark Prins	 */
419628e43ccSMark Prins	public function drawGPX() {
420c977deacSMark Prins		$col = imagecolorallocatealpha ( $this->image, 0, 0, 255, .4 * 127 );
4216c6bb022SMark Prins		$gpxgeom = geoPHP::load ( file_get_contents ( $this->gpxFileName ), 'gpx' );
422c977deacSMark Prins		$this->drawGeometry ( $gpxgeom, $col );
423628e43ccSMark Prins	}
424628e43ccSMark Prins
4256914b920SMark Prins	/**
4266914b920SMark Prins	 * Draw geojson on the map.
4276914b920SMark Prins	 */
4286914b920SMark Prins	public function drawGeojson() {
4296914b920SMark Prins		$col = imagecolorallocatealpha ( $this->image, 255, 0, 255, .4 * 127 );
4306914b920SMark Prins		$gpxgeom = geoPHP::load ( file_get_contents ( $this->geojsonFileName ), 'json' );
4316914b920SMark Prins		$this->drawGeometry ( $gpxgeom, $col );
4326914b920SMark Prins	}
43357e65445SMark Prins
434628e43ccSMark Prins	/**
435628e43ccSMark Prins	 * Draw kml trace on the map.
436628e43ccSMark Prins	 */
437628e43ccSMark Prins	public function drawKML() {
4382d11d700SMark Prins		// TODO get colour from kml node (not currently supported in geoPHP)
439c977deacSMark Prins		$col = imagecolorallocatealpha ( $this->image, 255, 0, 0, .4 * 127 );
440c977deacSMark Prins		$kmlgeom = geoPHP::load ( file_get_contents ( $this->kmlFileName ), 'kml' );
441c977deacSMark Prins		$this->drawGeometry ( $kmlgeom, $col );
442c977deacSMark Prins	}
44357e65445SMark Prins
444c977deacSMark Prins	/**
445c977deacSMark Prins	 * Draw geometry or geometry collection on the map.
446*ab8cbd2bSMark Prins	 *
447c977deacSMark Prins	 * @param Geometry $geom
448*ab8cbd2bSMark Prins	 * @param int $colour
449*ab8cbd2bSMark Prins	 *        	drawing colour
450c977deacSMark Prins	 */
451c977deacSMark Prins	private function drawGeometry($geom, $colour) {
4526c6bb022SMark Prins		switch ($geom->geometryType ()) {
453c977deacSMark Prins			case 'GeometryCollection' :
454c977deacSMark Prins				// recursively draw part of the collection
455c977deacSMark Prins				for($i = 1; $i < $geom->numGeometries () + 1; $i ++) {
456c977deacSMark Prins					$_geom = $geom->geometryN ( $i );
457c977deacSMark Prins					$this->drawGeometry ( $_geom, $colour );
458c977deacSMark Prins				}
4596c6bb022SMark Prins				break;
460c977deacSMark Prins			case 'MultiPolygon' :
461c977deacSMark Prins				// TODO implement / do nothing
462c977deacSMark Prins				break;
463c977deacSMark Prins			case 'MultiLineString' :
464c977deacSMark Prins				// TODO implement / do nothing
465c977deacSMark Prins				break;
466c977deacSMark Prins			case 'MultiPoint' :
467c977deacSMark Prins				// TODO implement / do nothing
4686c6bb022SMark Prins				break;
4696c6bb022SMark Prins			case 'Polygon' :
470c977deacSMark Prins				$this->drawPolygon ( $geom, $colour );
471c977deacSMark Prins				break;
472c977deacSMark Prins			case 'LineString' :
473c977deacSMark Prins				$this->drawLineString ( $geom, $colour );
474c977deacSMark Prins				break;
475c977deacSMark Prins			case 'Point' :
476c977deacSMark Prins				$this->drawPoint ( $geom, $colour );
4776c6bb022SMark Prins				break;
4786c6bb022SMark Prins			default :
4792d11d700SMark Prins				// draw nothing
4806c6bb022SMark Prins				break;
4816c6bb022SMark Prins		}
4826c6bb022SMark Prins	}
483c977deacSMark Prins
484e61425c7SMark Prins	/**
485e61425c7SMark Prins	 * Draw a line on the map.
486*ab8cbd2bSMark Prins	 *
487e61425c7SMark Prins	 * @param LineString $line
488*ab8cbd2bSMark Prins	 * @param int $colour
489*ab8cbd2bSMark Prins	 *        	drawing colour
490e61425c7SMark Prins	 */
491da6f229fSMark Prins	private function drawLineString($line, $colour) {
492cc74a83cSMark Prins		imagesetthickness ( $this->image, 2 );
493da6f229fSMark Prins		for($p = 1; $p < $line->numGeometries (); $p ++) {
494da6f229fSMark Prins			// get first pair of points
495da6f229fSMark Prins			$p1 = $line->geometryN ( $p );
496da6f229fSMark Prins			$p2 = $line->geometryN ( $p + 1 );
497da6f229fSMark Prins			// translate to paper space
498da6f229fSMark Prins			$x1 = floor ( ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile ( $p1->x (), $this->zoom )) );
499da6f229fSMark Prins			$y1 = floor ( ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile ( $p1->y (), $this->zoom )) );
500da6f229fSMark Prins			$x2 = floor ( ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile ( $p2->x (), $this->zoom )) );
501da6f229fSMark Prins			$y2 = floor ( ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile ( $p2->y (), $this->zoom )) );
502da6f229fSMark Prins			// draw to image
503da6f229fSMark Prins			imageline ( $this->image, $x1, $y1, $x2, $y2, $colour );
504da6f229fSMark Prins		}
505e61425c7SMark Prins		imagesetthickness ( $this->image, 1 );
506da6f229fSMark Prins	}
507c977deacSMark Prins
508e61425c7SMark Prins	/**
509e61425c7SMark Prins	 * Draw a point on the map.
510*ab8cbd2bSMark Prins	 *
511e61425c7SMark Prins	 * @param Point $point
512*ab8cbd2bSMark Prins	 * @param int $colour
513*ab8cbd2bSMark Prins	 *        	drawing colour
514e61425c7SMark Prins	 */
515da6f229fSMark Prins	private function drawPoint($point, $colour) {
516c977deacSMark Prins		imagesetthickness ( $this->image, 2 );
517da6f229fSMark Prins		// translate to paper space
518da6f229fSMark Prins		$cx = floor ( ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile ( $point->x (), $this->zoom )) );
519da6f229fSMark Prins		$cy = floor ( ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile ( $point->y (), $this->zoom )) );
520cc74a83cSMark Prins		$r = 5;
521da6f229fSMark Prins		// draw to image
522cc74a83cSMark Prins		// imageellipse($this->image, $cx, $cy,$r, $r, $colour);
523cc74a83cSMark Prins		imagefilledellipse ( $this->image, $cx, $cy, $r, $r, $colour );
524cc74a83cSMark Prins		// don't use imageellipse because the imagesetthickness function has
525c977deacSMark Prins		// no effect. So the better workaround is to use imagearc.
526cc74a83cSMark Prins		imagearc ( $this->image, $cx, $cy, $r, $r, 0, 359, $colour );
527e61425c7SMark Prins		imagesetthickness ( $this->image, 1 );
528da6f229fSMark Prins	}
529c977deacSMark Prins
530e61425c7SMark Prins	/**
531e61425c7SMark Prins	 * Draw a polygon on the map.
532*ab8cbd2bSMark Prins	 *
533e61425c7SMark Prins	 * @param Polygon $polygon
534*ab8cbd2bSMark Prins	 * @param int $colour
535*ab8cbd2bSMark Prins	 *        	drawing colour
536e61425c7SMark Prins	 */
537e61425c7SMark Prins	private function drawPolygon($polygon, $colour) {
538c977deacSMark Prins		// TODO implementation of drawing holes,
539c977deacSMark Prins		// maybe draw the polygon to an in-memory image and use imagecopy, draw polygon in col., draw holes in bgcol?
540c977deacSMark Prins
541c977deacSMark Prins		// print_r('Polygon:<br />');
542c977deacSMark Prins		// print_r($polygon);
543c977deacSMark Prins		$extPoints = array ();
544c977deacSMark Prins		// extring is a linestring actually..
545c977deacSMark Prins		$extRing = $polygon->exteriorRing ();
546c977deacSMark Prins
547c977deacSMark Prins		for($i = 1; $i < $extRing->numGeometries (); $i ++) {
548c977deacSMark Prins			$p1 = $extRing->geometryN ( $i );
549c977deacSMark Prins			$x = floor ( ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile ( $p1->x (), $this->zoom )) );
550c977deacSMark Prins			$y = floor ( ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile ( $p1->y (), $this->zoom )) );
551c977deacSMark Prins			$extPoints [] = $x;
552c977deacSMark Prins			$extPoints [] = $y;
553e61425c7SMark Prins		}
554c977deacSMark Prins		// print_r('points:('.($i-1).')<br />');
555c977deacSMark Prins		// print_r($extPoints);
556c977deacSMark Prins		// imagepolygon ($this->image, $extPoints, $i-1, $colour );
557c977deacSMark Prins		imagefilledpolygon ( $this->image, $extPoints, $i - 1, $colour );
558c977deacSMark Prins	}
559c977deacSMark Prins
560628e43ccSMark Prins	/**
561628e43ccSMark Prins	 * add copyright and origin notice and icons to the map.
562628e43ccSMark Prins	 */
563628e43ccSMark Prins	public function drawCopyright() {
564628e43ccSMark Prins		$logoBaseDir = dirname ( __FILE__ ) . '/' . 'logo/';
565628e43ccSMark Prins		$logoImg = imagecreatefrompng ( $logoBaseDir . $this->tileInfo ['openstreetmap'] ['logo'] );
566628e43ccSMark Prins		$textcolor = imagecolorallocate ( $this->image, 0, 0, 0 );
567628e43ccSMark Prins		$bgcolor = imagecolorallocate ( $this->image, 200, 200, 200 );
568628e43ccSMark Prins
5692d11d700SMark Prins		imagecopy ( $this->image, $logoImg, 0, imagesy ( $this->image ) - imagesy ( $logoImg ), 0, 0, imagesx ( $logoImg ), imagesy ( $logoImg ) );
570628e43ccSMark Prins		imagestring ( $this->image, 1, imagesx ( $logoImg ) + 2, imagesy ( $this->image ) - imagesy ( $logoImg ) + 1, $this->tileInfo ['openstreetmap'] ['txt'], $bgcolor );
571628e43ccSMark Prins		imagestring ( $this->image, 1, imagesx ( $logoImg ) + 1, imagesy ( $this->image ) - imagesy ( $logoImg ), $this->tileInfo ['openstreetmap'] ['txt'], $textcolor );
572628e43ccSMark Prins
573628e43ccSMark Prins		// additional tile source info, ie. who created/hosted the tiles
574628e43ccSMark Prins		if ($this->maptype != 'openstreetmap') {
575628e43ccSMark Prins			$iconImg = imagecreatefrompng ( $logoBaseDir . $this->tileInfo [$this->maptype] ['logo'] );
5762d11d700SMark Prins			imagecopy ( $this->image, $iconImg, imagesx ( $logoImg ) + 1, imagesy ( $this->image ) - imagesy ( $iconImg ), 0, 0, imagesx ( $iconImg ), imagesy ( $iconImg ) );
577628e43ccSMark Prins			imagestring ( $this->image, 1, imagesx ( $logoImg ) + imagesx ( $iconImg ) + 4, imagesy ( $this->image ) - ceil ( imagesy ( $logoImg ) / 2 ) + 1, $this->tileInfo [$this->maptype] ['txt'], $bgcolor );
578628e43ccSMark Prins			imagestring ( $this->image, 1, imagesx ( $logoImg ) + imagesx ( $iconImg ) + 3, imagesy ( $this->image ) - ceil ( imagesy ( $logoImg ) / 2 ), $this->tileInfo [$this->maptype] ['txt'], $textcolor );
579628e43ccSMark Prins		}
580628e43ccSMark Prins	}
581cc74a83cSMark Prins
582628e43ccSMark Prins	/**
583628e43ccSMark Prins	 * make the map.
584628e43ccSMark Prins	 */
585628e43ccSMark Prins	public function makeMap() {
586628e43ccSMark Prins		$this->initCoords ();
587628e43ccSMark Prins		$this->createBaseMap ();
588*ab8cbd2bSMark Prins		if (! empty ( $this->markers ))
589*ab8cbd2bSMark Prins			$this->placeMarkers ();
590*ab8cbd2bSMark Prins		if (file_exists ( $this->kmlFileName ))
591*ab8cbd2bSMark Prins			$this->drawKML ();
592*ab8cbd2bSMark Prins		if (file_exists ( $this->gpxFileName ))
593*ab8cbd2bSMark Prins			$this->drawGPX ();
594*ab8cbd2bSMark Prins		if (file_exists ( $this->geojsonFileName ))
595*ab8cbd2bSMark Prins			$this->drawGeojson ();
5966914b920SMark Prins
597628e43ccSMark Prins		$this->drawCopyright ();
598628e43ccSMark Prins	}
599cc74a83cSMark Prins
600628e43ccSMark Prins	/**
601e4f115f4SMark Prins	 * Calculate the lat/lon/zoom values to make sure that all of the markers and gpx/kml are on the map.
602*ab8cbd2bSMark Prins	 *
603*ab8cbd2bSMark Prins	 * @param float $paddingFactor
604*ab8cbd2bSMark Prins	 *        	buffer constant to enlarge (>1.0) the zoom level
6052d11d700SMark Prins	 */
6062d11d700SMark Prins	private function autoZoom($paddingFactor = 1.0) {
6072d11d700SMark Prins		$geoms = array ();
608e4f115f4SMark Prins		$geoms [] = new Point ( $this->lon, $this->lat );
609e4f115f4SMark Prins		if (! empty ( $this->markers )) {
6102d11d700SMark Prins			foreach ( $this->markers as $marker ) {
6112d11d700SMark Prins				$geoms [] = new Point ( $marker ['lon'], $marker ['lat'] );
6122d11d700SMark Prins			}
6132d11d700SMark Prins		}
6142d11d700SMark Prins		if (file_exists ( $this->kmlFileName )) {
6152d11d700SMark Prins			$geoms [] = geoPHP::load ( file_get_contents ( $this->kmlFileName ), 'kml' );
6162d11d700SMark Prins		}
6172d11d700SMark Prins		if (file_exists ( $this->gpxFileName )) {
6182d11d700SMark Prins			$geoms [] = geoPHP::load ( file_get_contents ( $this->gpxFileName ), 'gpx' );
6192d11d700SMark Prins		}
6206914b920SMark Prins		if (file_exists ( $this->geojsonFileName )) {
6216914b920SMark Prins			$geoms [] = geoPHP::load ( file_get_contents ( $this->geojsonFileName ), 'geojson' );
6226914b920SMark Prins		}
6236914b920SMark Prins
624*ab8cbd2bSMark Prins		if (count ( $geoms ) <= 1)
625*ab8cbd2bSMark Prins			return;
62653bfe4a3SMark Prins
6272d11d700SMark Prins		$geom = new GeometryCollection ( $geoms );
6282d11d700SMark Prins		$centroid = $geom->centroid ();
6292d11d700SMark Prins		$bbox = $geom->getBBox ();
6302d11d700SMark Prins
6312d11d700SMark Prins		// determine vertical resolution, this depends on the distance from the equator
6322d11d700SMark Prins		// $vy00 = log(tan(M_PI*(0.25 + $centroid->getY()/360)));
6332d11d700SMark Prins		$vy0 = log ( tan ( M_PI * (0.25 + $bbox ['miny'] / 360) ) );
6342d11d700SMark Prins		$vy1 = log ( tan ( M_PI * (0.25 + $bbox ['maxy'] / 360) ) );
63553bfe4a3SMark Prins		$zoomFactorPowered = ($this->height / 2) / (40.7436654315252 * ($vy1 - $vy0));
6362d11d700SMark Prins		$resolutionVertical = 360 / ($zoomFactorPowered * $this->tileSize);
6372d11d700SMark Prins		// determine horizontal resolution
6382d11d700SMark Prins		$resolutionHorizontal = ($bbox ['maxx'] - $bbox ['minx']) / $this->width;
6392d11d700SMark Prins		$resolution = max ( $resolutionHorizontal, $resolutionVertical ) * $paddingFactor;
6402d11d700SMark Prins		$zoom = log ( 360 / ($resolution * $this->tileSize), 2 );
6412d11d700SMark Prins
6422d11d700SMark Prins		$this->zoom = floor ( $zoom );
6432d11d700SMark Prins		$this->lon = $centroid->getX ();
6442d11d700SMark Prins		$this->lat = $centroid->getY ();
6452d11d700SMark Prins	}
6462d11d700SMark Prins
6472d11d700SMark Prins	/**
648628e43ccSMark Prins	 * get the map, this may return a reference to a cached copy.
649*ab8cbd2bSMark Prins	 *
650628e43ccSMark Prins	 * @return string url relative to media dir
651628e43ccSMark Prins	 */
652628e43ccSMark Prins	public function getMap() {
653*ab8cbd2bSMark Prins		if ($this->autoZoomExtent)
654*ab8cbd2bSMark Prins			$this->autoZoom ();
6552d11d700SMark Prins
656628e43ccSMark Prins			// use map cache, so check cache for map
657628e43ccSMark Prins		if (! $this->checkMapCache ()) {
658628e43ccSMark Prins			// map is not in cache, needs to be build
659628e43ccSMark Prins			$this->makeMap ();
660628e43ccSMark Prins			$this->mkdir_recursive ( dirname ( $this->mapCacheIDToFilename () ), 0777 );
661628e43ccSMark Prins			imagepng ( $this->image, $this->mapCacheIDToFilename (), 9 );
662628e43ccSMark Prins		}
663628e43ccSMark Prins		$this->doc = $this->mapCacheIDToFilename ();
664628e43ccSMark Prins		// make url relative to media dir
665628e43ccSMark Prins		return str_replace ( $this->mediaBaseDir, '', $this->doc );
666628e43ccSMark Prins	}
667628e43ccSMark Prins}
668