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