xref: /plugin/openlayersmap/StaticMap.php (revision 0d370c81d8b01dcc045626b9408ac87883fc8a41)
1<?php
2
3/*
4 * Copyright (c) 2012-2026 Mark C. Prins <mprins@users.sf.net>
5 *
6 * In part based on staticMapLite 0.03 available at http://staticmaplite.svn.sourceforge.net/viewvc/staticmaplite/
7 *
8 * Copyright (c) 2009 Gerhard Koch <gerhard.koch AT ymail.com>
9 *
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 *     http://www.apache.org/licenses/LICENSE-2.0
15 *
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 */
22namespace dokuwiki\plugin\openlayersmap;
23
24use Exception;
25use GdImage;
26use geoPHP\Geometry\Geometry;
27use geoPHP\Geometry\GeometryCollection;
28use geoPHP\Geometry\LineString;
29use geoPHP\Geometry\MultiLineString;
30use geoPHP\Geometry\MultiPoint;
31use geoPHP\Geometry\MultiPolygon;
32use geoPHP\Geometry\Point;
33use geoPHP\Geometry\Polygon;
34use geoPHP\geoPHP;
35use dokuwiki\HTTP\DokuHTTPClient;
36use dokuwiki\Logger;
37
38/**
39 *
40 * @author Mark C. Prins <mprins@users.sf.net>
41 * @author Gerhard Koch <gerhard.koch AT ymail.com>
42 *
43 */
44class StaticMap
45{
46    // the final output
47    private int $tileSize = 256;
48    private array $tileInfo = [
49        // OSM sources
50        'openstreetmap' => ['txt' => '(c) OpenStreetMap data/ODbL', 'logo' => 'osm_logo.png',
51            'url' => 'https://tile.openstreetmap.org/{Z}/{X}/{Y}.png'],
52        // OpenTopoMap sources
53        'opentopomap' => ['txt' => '(c) OpenStreetMap data/ODbL, SRTM | style: (c) OpenTopoMap',
54            'logo' => 'osm_logo.png', 'url' => 'https://tile.opentopomap.org/{Z}/{X}/{Y}.png'],
55        // OCM sources
56        'cycle' => ['txt' => '(c) Thunderforest maps', 'logo' => 'tf_logo.png',
57            'url' => 'https://tile.thunderforest.com/cycle/{Z}/{X}/{Y}.png'],
58        'transport' => ['txt' => '(c) Thunderforest maps', 'logo' => 'tf_logo.png',
59            'url' => 'https://tile.thunderforest.com/transport/{Z}/{X}/{Y}.png'],
60        'landscape' => ['txt' => '(c) Thunderforest maps', 'logo' => 'tf_logo.png',
61            'url' => 'https://tile.thunderforest.com/landscape/{Z}/{X}/{Y}.png'],
62        'outdoors' => ['txt' => '(c) Thunderforest maps', 'logo' => 'tf_logo.png',
63            'url' => 'https://tile.thunderforest.com/outdoors/{Z}/{X}/{Y}.png'],
64        'toner' => ['txt' => '(c) Stadia Maps;Stamen Design;OpenStreetMap contributors', 'logo' => 'stamen.png',
65            'url' => 'https://tiles-eu.stadiamaps.com/tiles/stamen_toner/{Z}/{X}/{Y}.png'],
66        'terrain' => ['txt' => '(c) Stadia Maps;Stamen Design;OpenStreetMap contributors', 'logo' => 'stamen.png',
67            'url' => 'https://tiles-eu.stadiamaps.com/tiles/stamen_terrain/{Z}/{X}/{Y}.png'],
68    ];
69    private string $tileDefaultSrc = 'openstreetmap';
70
71    // set up markers
72    private array $markerPrototypes = [
73        // found at http://www.mapito.net/map-marker-icons.html
74        // these are 17x19 px with a pointer at the bottom left
75        'lightblue' => ['regex' => '/^lightblue(\d+)$/', 'extension' => '.png', 'shadow' => false,
76            'offsetImage' => '0,-19', 'offsetShadow' => false],
77        // openlayers std markers are 21x25px with shadow
78        'ol-marker' => ['regex' => '/^marker(|-blue|-gold|-green|-red)+$/', 'extension' => '.png',
79            'shadow' => 'marker_shadow.png', 'offsetImage' => '-10,-25', 'offsetShadow' => '-1,-13'],
80        // these are 16x16 px
81        'ww_icon' => ['regex' => '/ww_\S+$/', 'extension' => '.png', 'shadow' => false, 'offsetImage' => '-8,-8',
82            'offsetShadow' => false],
83        // assume these are 16x16 px
84        'rest' => ['regex' => '/^(?!lightblue(\d+)$)(?!(ww_\S+$))(?!marker(|-blue|-gold|-green|-red)+$)(.*)/',
85            'extension' => '.png', 'shadow' => 'marker_shadow.png', 'offsetImage' => '-8,-8',
86            'offsetShadow' => '-1,-1'],
87    ];
88    // note even though $centerX, $centerY, $offsetX and $offsetY are defined as float,
89    //   these are actually integer numbers, but the php floor()/ceil() functions return a float
90    private float $centerX;
91    private float $centerY;
92    private float $offsetX;
93    private float $offsetY;
94    private $image;
95    private int $zoom;
96    private float $lat;
97    private float $lon;
98    private readonly int $width;
99    private readonly int $height;
100    private readonly array $markers;
101    private string $maptype;
102    private readonly string $kmlFileName;
103    private readonly string $gpxFileName;
104    private readonly string $geojsonFileName;
105    private readonly bool $autoZoomExtent;
106    private readonly string $apikey;
107    private readonly string $tileCacheBaseDir;
108    private readonly string $mapCacheBaseDir;
109    private readonly string $mediaBaseDir;
110    private readonly bool $useTileCache;
111    private string $mapCacheID = '';
112    private string $mapCacheFile = '';
113    private string $mapCacheExtension = 'png';
114
115    /**
116     * Constructor.
117     *
118     * @param float  $lat
119     *            Latitude (x) of center of map
120     * @param float  $lon
121     *            Longitude (y) of center of map
122     * @param int    $zoom
123     *            Zoomlevel
124     * @param int    $width
125     *            Width in pixels
126     * @param int    $height
127     *            Height in pixels
128     * @param string $maptype
129     *            Name of the map
130     * @param array  $markers
131     *            array of markers
132     * @param string $gpx
133     *            GPX filename
134     * @param string $kml
135     *            KML filename
136     * @param string $geojson
137     * @param string $mediaDir
138     *            Directory to store/cache maps
139     * @param string $tileCacheBaseDir
140     *            Directory to cache map tiles
141     * @param bool   $autoZoomExtent
142     *            Wheter or not to override zoom/lat/lon and zoom to the extent of gpx/kml and markers
143     * @param string $apikey
144     */
145    public function __construct(
146        float $lat,
147        float $lon,
148        int $zoom,
149        int $width,
150        int $height,
151        string $maptype,
152        array $markers,
153        string $gpx,
154        string $kml,
155        string $geojson,
156        string $mediaDir,
157        string $tileCacheBaseDir,
158        bool $autoZoomExtent = true,
159        string $apikey = ''
160    ) {
161        $this->zoom   = $zoom;
162        $this->lat    = $lat;
163        $this->lon    = $lon;
164        $this->width  = $width;
165        $this->height = $height;
166        // validate + set maptype
167        $this->maptype = $this->tileDefaultSrc;
168        if (array_key_exists($maptype, $this->tileInfo)) {
169            $this->maptype = $maptype;
170        }
171        $this->markers          = $markers;
172        $this->kmlFileName      = $kml;
173        $this->gpxFileName      = $gpx;
174        $this->geojsonFileName  = $geojson;
175        $this->mediaBaseDir     = $mediaDir;
176        $this->tileCacheBaseDir = $tileCacheBaseDir . '/olmaptiles';
177        $this->useTileCache     = $this->tileCacheBaseDir !== '';
178        $this->mapCacheBaseDir  = $mediaDir . '/olmapmaps';
179        $this->autoZoomExtent   = $autoZoomExtent;
180        $this->apikey           = $apikey;
181        $this->mapCacheID       = md5(implode(
182            "&",
183            [
184                $this->zoom,
185                $this->lat,
186                $this->lon,
187                $this->width,
188                $this->height,
189                serialize($this->markers),
190                $this->maptype,
191                $this->kmlFileName,
192                $this->gpxFileName,
193                $this->geojsonFileName
194            ]
195        ));
196    }
197
198    /**
199     * get the map, this may return a reference to a cached copy.
200     *
201     * @return string url relative to media dir
202     */
203    public function getMap(): string
204    {
205        try {
206            if ($this->autoZoomExtent) {
207                $this->autoZoom();
208            }
209        } catch (Exception $e) {
210            Logger::debug($e);
211        }
212
213        $filename = $this->mapCacheIDToFilename();
214        // use map cache, so check cache for map
215        if (!$this->checkMapCache()) {
216            // map is not in cache, needs to be build
217            $this->makeMap();
218            $this->mkdirRecursive(dirname($filename), 0777);
219            imagepng($this->image, $filename, 9);
220        }
221        // make url relative to media dir
222        return str_replace($this->mediaBaseDir, '', $filename);
223    }
224
225    /**
226     * Calculate the lat/lon/zoom values to make sure that all of the markers and gpx/kml are on the map.
227     *
228     * @param float $paddingFactor
229     *            buffer constant to enlarge (>1.0) the zoom level
230     * @throws Exception if non-geometries are found in the collection
231     */
232    private function autoZoom(float $paddingFactor = 1.0): void
233    {
234        $geoms    = [];
235        $geoms [] = new Point($this->lon, $this->lat);
236        if ($this->markers !== []) {
237            foreach ($this->markers as $marker) {
238                $geoms [] = new Point($marker ['lon'], $marker ['lat']);
239            }
240        }
241        if (file_exists($this->kmlFileName)) {
242            $g = geoPHP::load(file_get_contents($this->kmlFileName), 'kml');
243            if ($g !== false) {
244                $geoms [] = $g;
245            }
246        }
247        if (file_exists($this->gpxFileName)) {
248            $g = geoPHP::load(file_get_contents($this->gpxFileName), 'gpx');
249            if ($g !== false) {
250                $geoms [] = $g;
251            }
252        }
253        if (file_exists($this->geojsonFileName)) {
254            $g = geoPHP::load(file_get_contents($this->geojsonFileName), 'geojson');
255            if ($g !== false) {
256                $geoms [] = $g;
257            }
258        }
259
260        if (count($geoms) <= 1) {
261            Logger::debug("StaticMap::autoZoom: Skip setting autozoom options", $geoms);
262            return;
263        }
264
265        $geom     = new GeometryCollection($geoms);
266        $centroid = $geom->centroid();
267        $bbox     = $geom->getBBox();
268
269        // determine vertical resolution, this depends on the distance from the equator
270        // $vy00 = log(tan(M_PI*(0.25 + $centroid->getY()/360)));
271        $vy0 = log(tan(M_PI * (0.25 + $bbox ['miny'] / 360)));
272        $vy1 = log(tan(M_PI * (0.25 + $bbox ['maxy'] / 360)));
273        Logger::debug("StaticMap::autoZoom: vertical resolution: $vy0, $vy1");
274        if ($vy1 - $vy0 === 0.0) {
275            $resolutionVertical = 0;
276            Logger::debug("StaticMap::autoZoom: using $resolutionVertical");
277        } else {
278            $zoomFactorPowered  = ($this->height / 2) / (40.7436654315252 * ($vy1 - $vy0));
279            $resolutionVertical = 360 / ($zoomFactorPowered * $this->tileSize);
280        }
281        // determine horizontal resolution
282        $resolutionHorizontal = ($bbox ['maxx'] - $bbox ['minx']) / $this->width;
283        Logger::debug("StaticMap::autoZoom: using $resolutionHorizontal");
284        $resolution           = max($resolutionHorizontal, $resolutionVertical) * $paddingFactor;
285        $zoom                 = $this->zoom;
286        if ($resolution > 0) {
287            $zoom             = log(360 / ($resolution * $this->tileSize), 2);
288        }
289
290        if (is_finite($zoom) && $zoom < 15 && $zoom > 2) {
291            $this->zoom = floor($zoom);
292        }
293        $this->lon = $centroid->getX();
294        $this->lat = $centroid->getY();
295        Logger::debug("Set staticmap autozoom options to: z: $this->zoom, lon: $this->lon, lat: $this->lat");
296    }
297
298    private function checkMapCache(): bool
299    {
300        $filename = $this->mapCacheIDToFilename();
301        return file_exists($filename);
302    }
303
304    private function mapCacheIDToFilename(): string
305    {
306        if (!$this->mapCacheFile) {
307            $this->mapCacheFile = $this->mapCacheBaseDir . "/" . $this->maptype . "/" . $this->zoom . "/cache_"
308                . substr($this->mapCacheID, 0, 2) . "/" . substr($this->mapCacheID, 2, 2)
309                . "/" . substr($this->mapCacheID, 4);
310        }
311        return $this->mapCacheFile . "." . $this->mapCacheExtension;
312    }
313
314    /**
315     * make the map.
316     */
317    public function makeMap(): void
318    {
319        $this->initCoords();
320        $this->createBaseMap();
321        if ($this->markers !== []) {
322            $this->placeMarkers();
323        }
324        if (file_exists($this->kmlFileName)) {
325            try {
326                $this->drawKML();
327            } catch (exception $e) {
328                Logger::error('failed to load KML file', $e);
329            }
330        }
331        if (file_exists($this->gpxFileName)) {
332            try {
333                $this->drawGPX();
334            } catch (exception $e) {
335                Logger::error('failed to load GPX file', $e);
336            }
337        }
338        if (file_exists($this->geojsonFileName)) {
339            try {
340                $this->drawGeojson();
341            } catch (exception $e) {
342                Logger::error('failed to load GeoJSON file', $e);
343            }
344        }
345
346        $this->drawCopyright();
347    }
348
349    /**
350     */
351    public function initCoords(): void
352    {
353        $this->centerX = $this->lonToTile($this->lon, $this->zoom);
354        $this->centerY = $this->latToTile($this->lat, $this->zoom);
355        $this->offsetX = floor((floor($this->centerX) - $this->centerX) * $this->tileSize);
356        $this->offsetY = floor((floor($this->centerY) - $this->centerY) * $this->tileSize);
357    }
358
359    /**
360     *
361     * @param float $long
362     * @param int   $zoom
363     * @return float
364     */
365    public function lonToTile(float $long, int $zoom): float
366    {
367        return (($long + 180) / 360) * 2 ** $zoom;
368    }
369
370    /**
371     *
372     * @param float $lat
373     * @param int   $zoom
374     * @return float
375     */
376    public function latToTile(float $lat, int $zoom): float
377    {
378        return (1 - log(tan($lat * M_PI / 180) + 1 / cos($lat * M_PI / 180)) / M_PI) / 2 * 2 ** $zoom;
379    }
380
381    /**
382     * make basemap image.
383     */
384    public function createBaseMap(): void
385    {
386        $this->image   = imagecreatetruecolor($this->width, $this->height);
387        $startX        = floor($this->centerX - ($this->width / $this->tileSize) / 2);
388        $startY        = floor($this->centerY - ($this->height / $this->tileSize) / 2);
389        $endX          = ceil($this->centerX + ($this->width / $this->tileSize) / 2);
390        $endY          = ceil($this->centerY + ($this->height / $this->tileSize) / 2);
391        $this->offsetX = -floor(($this->centerX - floor($this->centerX)) * $this->tileSize);
392        $this->offsetY = -floor(($this->centerY - floor($this->centerY)) * $this->tileSize);
393        $this->offsetX += floor($this->width / 2);
394        $this->offsetY += floor($this->height / 2);
395        $this->offsetX += floor($startX - floor($this->centerX)) * $this->tileSize;
396        $this->offsetY += floor($startY - floor($this->centerY)) * $this->tileSize;
397
398        for ($x = $startX; $x <= $endX; $x++) {
399            for ($y = $startY; $y <= $endY; $y++) {
400                $url = str_replace(
401                    ['{Z}', '{X}', '{Y}'],
402                    [$this->zoom, $x, $y],
403                    $this->tileInfo [$this->maptype] ['url']
404                );
405
406                $tileData = $this->fetchTile($url);
407                if ($tileData) {
408                    $tileImage = imagecreatefromstring($tileData);
409                }
410                if (!$tileData || $tileImage === false || !$tileImage instanceof GdImage) {
411                    $tileImage = imagecreate($this->tileSize, $this->tileSize);
412                    $color     = imagecolorallocate($tileImage, 255, 255, 255);
413                    @imagestring($tileImage, 1, 127, 127, 'err', $color);
414                }
415                $destX = (int) ($x - $startX) * $this->tileSize + $this->offsetX;
416                $destY = (int) ($y - $startY) * $this->tileSize + $this->offsetY;
417                Logger::debug("imagecopy tile into image: $destX, $destY", $this->tileSize);
418                imagecopy(
419                    $this->image,
420                    $tileImage,
421                    $destX,
422                    $destY,
423                    0,
424                    0,
425                    $this->tileSize,
426                    $this->tileSize
427                );
428            }
429        }
430    }
431
432    /**
433     * Fetch a tile (from the source or from the cache) and optionally store it in the cache,
434     * returns false if the tile is not a valid image.
435     * @param string $url
436     * @return bool|string
437     */
438    public function fetchTile(string $url): bool|string
439    {
440        if ($this->useTileCache) {
441            $cached = $this->checkTileCache($url);
442            if ($cached) {
443                return $cached;
444            }
445        }
446
447        $client = new DokuHTTPClient();
448        $client->agent = 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; ' . PHP_OS . ')';
449        $client->referer = DOKU_URL;
450        Logger::debug("fetchTile: getting: $url using DokuHTTPClient");
451        $tile = $client->get($url . $this->apikey);
452
453        // check if we retrieved a valid image
454        if ($tile !== false && @imagecreatefromstring($tile) !== false) {
455            if ($this->useTileCache) {
456                $this->writeTileToCache($url, $tile);
457            }
458            return $tile;
459        }
460        return false;
461    }
462
463    /**
464     *
465     * @param string $url
466     * @return string|false
467     */
468    public function checkTileCache(string $url): string|false
469    {
470        $filename = $this->tileUrlToFilename($url);
471        if (file_exists($filename)) {
472            return file_get_contents($filename);
473        }
474        return false;
475    }
476
477    /**
478     * @param string $url
479     * @return string
480     */
481    public function tileUrlToFilename(string $url): string
482    {
483        return $this->tileCacheBaseDir . "/" . substr($url, strpos($url, '/') + 1);
484    }
485
486    /**
487     * Write a tile into the cache.
488     *
489     * @param string $url
490     * @param mixed  $data
491     */
492    public function writeTileToCache(string $url, mixed $data): void
493    {
494        $filename = $this->tileUrlToFilename($url);
495        $this->mkdirRecursive(dirname($filename), 0777);
496        file_put_contents($filename, $data);
497    }
498
499    /**
500     * Recursively create the directory.
501     *
502     * @param string $pathname
503     *            The directory path.
504     * @param int    $mode
505     *            File access mode. For more information on modes, read the details on the chmod manpage.
506     */
507    public function mkdirRecursive(string $pathname, int $mode): bool
508    {
509        if (!is_dir(dirname($pathname))) {
510            $this->mkdirRecursive(dirname($pathname), $mode);
511        }
512        return is_dir($pathname) || mkdir($pathname, $mode) || is_dir($pathname);
513    }
514
515    /**
516     * Place markers on the map and number them in the same order as they are listed in the html.
517     */
518    public function placeMarkers(): void
519    {
520        $count         = 0;
521        $color         = imagecolorallocate($this->image, 0, 0, 0);
522        $bgcolor       = imagecolorallocate($this->image, 200, 200, 200);
523        $markerBaseDir = __DIR__ . '/icons';
524        $markerImageOffsetX  = 0;
525        $markerImageOffsetY  = 0;
526        $markerShadowOffsetX = 0;
527        $markerShadowOffsetY = 0;
528        $markerShadowImg     = null;
529        // loop thru marker array
530        foreach ($this->markers as $marker) {
531            // set some local variables
532            $markerLat  = $marker ['lat'];
533            $markerLon  = $marker ['lon'];
534            $markerType = $marker ['type'];
535            // clear variables from previous loops
536            $markerFilename = '';
537            $markerShadow   = '';
538            $matches        = false;
539            // check for marker type, get settings from markerPrototypes
540            if ($markerType) {
541                foreach ($this->markerPrototypes as $markerPrototype) {
542                    if (preg_match($markerPrototype ['regex'], $markerType, $matches)) {
543                        $markerFilename = $matches [0] . $markerPrototype ['extension'];
544                        if ($markerPrototype ['offsetImage']) {
545                            [$markerImageOffsetX, $markerImageOffsetY] = explode(
546                                ",",
547                                $markerPrototype ['offsetImage']
548                            );
549                        }
550                        $markerShadow = $markerPrototype ['shadow'];
551                        if ($markerShadow) {
552                            [$markerShadowOffsetX, $markerShadowOffsetY] = explode(
553                                ",",
554                                $markerPrototype ['offsetShadow']
555                            );
556                        }
557                    }
558                }
559            }
560            // create img resource
561            if (file_exists($markerBaseDir . '/' . $markerFilename)) {
562                $markerImg = imagecreatefrompng($markerBaseDir . '/' . $markerFilename);
563            } else {
564                $markerImg = imagecreatefrompng($markerBaseDir . '/marker.png');
565            }
566            // check for shadow + create shadow recource
567            if ($markerShadow && file_exists($markerBaseDir . '/' . $markerShadow)) {
568                $markerShadowImg = imagecreatefrompng($markerBaseDir . '/' . $markerShadow);
569            }
570            // calc position
571            $destX = (int) floor(
572                ($this->width / 2) -
573                $this->tileSize * ($this->centerX - $this->lonToTile($markerLon, $this->zoom))
574            );
575            $destY = (int) floor(
576                ($this->height / 2) -
577                $this->tileSize * ($this->centerY - $this->latToTile($markerLat, $this->zoom))
578            );
579            // copy shadow on basemap
580            if ($markerShadow && $markerShadowImg) {
581                imagecopy(
582                    $this->image,
583                    $markerShadowImg,
584                    $destX + (int) $markerShadowOffsetX,
585                    $destY + (int) $markerShadowOffsetY,
586                    0,
587                    0,
588                    imagesx($markerShadowImg),
589                    imagesy($markerShadowImg)
590                );
591            }
592            // copy marker on basemap above shadow
593            imagecopy(
594                $this->image,
595                $markerImg,
596                $destX + (int) $markerImageOffsetX,
597                $destY + (int) $markerImageOffsetY,
598                0,
599                0,
600                imagesx($markerImg),
601                imagesy($markerImg)
602            );
603            // add label
604            imagestring(
605                $this->image,
606                3,
607                $destX - imagesx($markerImg) + 1,
608                $destY + (int) $markerImageOffsetY + 1,
609                ++$count,
610                $bgcolor
611            );
612            imagestring(
613                $this->image,
614                3,
615                $destX - imagesx($markerImg),
616                $destY + (int) $markerImageOffsetY,
617                $count,
618                $color
619            );
620        }
621    }
622
623    /**
624     * Draw kml trace on the map.
625     * @throws Exception when loading the KML fails
626     */
627    public function drawKML(): void
628    {
629        // TODO get colour from kml node (not currently supported in geoPHP)
630        $col     = imagecolorallocatealpha($this->image, 255, 0, 0, 50);
631        $kmlgeom = geoPHP::load(file_get_contents($this->kmlFileName), 'kml');
632        $this->drawGeometry($kmlgeom, $col);
633    }
634
635    /**
636     * Draw geometry or geometry collection on the map.
637     *
638     * @param Geometry $geom
639     * @param int      $colour
640     *            drawing colour
641     */
642    private function drawGeometry(Geometry $geom, int $colour): void
643    {
644        if (empty($geom)) {
645            return;
646        }
647
648        switch ($geom->geometryType()) {
649            case 'GeometryCollection':
650                // recursively draw parts of the collection
651                for ($i = 1; $i < $geom->numGeometries() + 1; $i++) {
652                    $_geom = $geom->geometryN($i);
653                    $this->drawGeometry($_geom, $colour);
654                }
655                break;
656            case 'Polygon':
657                /** @var Polygon $geom */
658                $this->drawPolygon($geom, $colour);
659                break;
660            case 'LineString':
661                /** @var LineString $geom */
662                $this->drawLineString($geom, $colour);
663                break;
664            case 'Point':
665                /** @var Point $geom */
666                $this->drawPoint($geom, $colour);
667                break;
668            case 'MultiPolygon':
669                /** @var MultiPolygon $geom */
670                for ($i = 1; $i < $geom->numGeometries() + 1; $i++) {
671                    $_poly = $geom->geometryN($i);
672                    $this->drawGeometry($_poly, $colour);
673                }
674                break;
675            case 'MultiLineString':
676                /** @var MultiLineString $geom */
677                for ($i = 1; $i < $geom->numGeometries() + 1; $i++) {
678                    $_line = $geom->geometryN($i);
679                    $this->drawGeometry($_line, $colour);
680                }
681                break;
682            case 'MultiPoint':
683                /** @var MultiPoint $geom */
684                for ($i = 1; $i < $geom->numPoints() + 1; $i++) {
685                    $_p = $geom->geometryN($i);
686                    $this->drawGeometry($_p, $colour);
687                }
688                break;
689            default:
690                // draw nothing
691                break;
692        }
693    }
694
695    /**
696     * Draw a polygon on the map.
697     *
698     * @param Polygon $polygon
699     * @param int     $colour
700     *            drawing colour
701     */
702    private function drawPolygon(Polygon $polygon, int $colour): void
703    {
704        // TODO implementation of drawing holes,
705        // maybe draw the polygon to an in-memory image and use imagecopy, draw polygon in col., draw holes in bgcol?
706
707        // print_r('Polygon:<br />');
708        // print_r($polygon);
709        $extPoints = [];
710        // extRing is a linestring actually...
711        $extRing = $polygon->exteriorRing();
712
713        for ($i = 1; $i < $extRing->numGeometries(); $i++) {
714            $p1 = $extRing->geometryN($i);
715            $x  = floor(
716                ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom))
717            );
718            $y  = floor(
719                ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p1->y(), $this->zoom))
720            );
721            $extPoints [] = $x;
722            $extPoints [] = $y;
723        }
724        // print_r('points:('.($i-1).')<br />');
725        // print_r($extPoints);
726        // imagepolygon ($this->image, $extPoints, $i-1, $colour );
727        imagefilledpolygon($this->image, $extPoints, $colour);
728    }
729
730    /**
731     * Draw a line on the map.
732     *
733     * @param LineString $line
734     * @param int $colour
735     *            drawing colour
736     */
737    private function drawLineString(LineString $line, int $colour): void
738    {
739        imagesetthickness($this->image, 2);
740        for ($p = 1; $p < $line->numGeometries(); $p++) {
741            // get first pair of points
742            $p1 = $line->geometryN($p);
743            $p2 = $line->geometryN($p + 1);
744            // translate to paper space
745            $x1 = floor(
746                ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom))
747            );
748            $y1 = floor(
749                ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p1->y(), $this->zoom))
750            );
751            $x2 = floor(
752                ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p2->x(), $this->zoom))
753            );
754            $y2 = floor(
755                ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p2->y(), $this->zoom))
756            );
757            // draw to image
758            imageline($this->image, $x1, $y1, $x2, $y2, $colour);
759        }
760        imagesetthickness($this->image, 1);
761    }
762
763    /**
764     * Draw a point on the map.
765     *
766     * @param Point $point
767     * @param int $colour
768     *            drawing colour
769     */
770    private function drawPoint(Point $point, int $colour): void
771    {
772        imagesetthickness($this->image, 2);
773        // translate to paper space
774        $cx = floor(
775            ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($point->x(), $this->zoom))
776        );
777        $cy = floor(
778            ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($point->y(), $this->zoom))
779        );
780        $r  = 5;
781        // draw to image
782        // imageellipse($this->image, $cx, $cy,$r, $r, $colour);
783        imagefilledellipse($this->image, $cx, $cy, $r, $r, $colour);
784        // don't use imageellipse because the imagesetthickness function has
785        // no effect. So the better workaround is to use imagearc.
786        imagearc($this->image, $cx, $cy, $r, $r, 0, 359, $colour);
787        imagesetthickness($this->image, 1);
788    }
789
790    /**
791     * Draw gpx trace on the map.
792     * @throws Exception when loading the GPX fails
793     */
794    public function drawGPX(): void
795    {
796        $col     = imagecolorallocatealpha($this->image, 0, 0, 255, 50);
797        $gpxgeom = geoPHP::load(file_get_contents($this->gpxFileName), 'gpx');
798        $this->drawGeometry($gpxgeom, $col);
799    }
800
801    /**
802     * Draw geojson on the map.
803     * @throws Exception when loading the JSON fails
804     */
805    public function drawGeojson(): void
806    {
807        $col     = imagecolorallocatealpha($this->image, 255, 0, 255, 50);
808        $jsonGeom = geoPHP::load(file_get_contents($this->geojsonFileName), 'json');
809        $this->drawGeometry($jsonGeom, $col);
810    }
811
812    /**
813     * add copyright and origin notice and icons to the map.
814     */
815    public function drawCopyright(): void
816    {
817        $logoBaseDir = __DIR__ . '/' . 'logo/';
818        $logoImg     = imagecreatefrompng($logoBaseDir . $this->tileInfo ['openstreetmap'] ['logo']);
819        $textcolor   = imagecolorallocate($this->image, 0, 0, 0);
820        $bgcolor     = imagecolorallocate($this->image, 200, 200, 200);
821
822        imagecopy(
823            $this->image,
824            $logoImg,
825            0,
826            imagesy($this->image) - imagesy($logoImg),
827            0,
828            0,
829            imagesx($logoImg),
830            imagesy($logoImg)
831        );
832        imagestring(
833            $this->image,
834            1,
835            imagesx($logoImg) + 2,
836            imagesy($this->image) - imagesy($logoImg) + 1,
837            $this->tileInfo ['openstreetmap'] ['txt'],
838            $bgcolor
839        );
840        imagestring(
841            $this->image,
842            1,
843            imagesx($logoImg) + 1,
844            imagesy($this->image) - imagesy($logoImg),
845            $this->tileInfo ['openstreetmap'] ['txt'],
846            $textcolor
847        );
848
849        // additional tile source info, ie. who created/hosted the tiles
850        $xIconOffset = 0;
851        if ($this->maptype === 'openstreetmap') {
852            $mapAuthor = "(c) OpenStreetMap maps/CC BY-SA";
853        } else {
854            $mapAuthor   = $this->tileInfo [$this->maptype] ['txt'];
855            $iconImg     = imagecreatefrompng($logoBaseDir . $this->tileInfo [$this->maptype] ['logo']);
856            $xIconOffset = imagesx($iconImg);
857            imagecopy(
858                $this->image,
859                $iconImg,
860                imagesx($logoImg) + 1,
861                imagesy($this->image) - imagesy($iconImg),
862                0,
863                0,
864                imagesx($iconImg),
865                imagesy($iconImg)
866            );
867        }
868        imagestring(
869            $this->image,
870            1,
871            imagesx($logoImg) + $xIconOffset + 4,
872            imagesy($this->image) - ceil(imagesy($logoImg) / 2) + 1,
873            $mapAuthor,
874            $bgcolor
875        );
876        imagestring(
877            $this->image,
878            1,
879            imagesx($logoImg) + $xIconOffset + 3,
880            imagesy($this->image) - ceil(imagesy($logoImg) / 2),
881            $mapAuthor,
882            $textcolor
883        );
884    }
885}
886