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 even though $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 [ 278 $this->zoom, 279 $this->lat, 280 $this->lon, 281 $this->width, 282 $this->height, 283 serialize($this->markers), 284 $this->maptype, 285 $this->kmlFileName, 286 $this->gpxFileName, 287 $this->geojsonFileName 288 ] 289 ); 290 } 291 292 public function mapCacheIDToFilename(): string 293 { 294 if (!$this->mapCacheFile) { 295 $this->mapCacheFile = $this->mapCacheBaseDir . "/" . $this->maptype . "/" . $this->zoom . "/cache_" 296 . substr($this->mapCacheID, 0, 2) . "/" . substr($this->mapCacheID, 2, 2) 297 . "/" . substr($this->mapCacheID, 4); 298 } 299 return $this->mapCacheFile . "." . $this->mapCacheExtension; 300 } 301 302 /** 303 * make the map. 304 */ 305 public function makeMap(): void 306 { 307 $this->initCoords(); 308 $this->createBaseMap(); 309 if ($this->markers !== []) { 310 $this->placeMarkers(); 311 } 312 if (file_exists($this->kmlFileName)) { 313 try { 314 $this->drawKML(); 315 } catch (exception $e) { 316 Logger::error('failed to load KML file', $e); 317 } 318 } 319 if (file_exists($this->gpxFileName)) { 320 try { 321 $this->drawGPX(); 322 } catch (exception $e) { 323 Logger::error('failed to load GPX file', $e); 324 } 325 } 326 if (file_exists($this->geojsonFileName)) { 327 try { 328 $this->drawGeojson(); 329 } catch (exception $e) { 330 Logger::error('failed to load GeoJSON file', $e); 331 } 332 } 333 334 $this->drawCopyright(); 335 } 336 337 /** 338 */ 339 public function initCoords(): void 340 { 341 $this->centerX = $this->lonToTile($this->lon, $this->zoom); 342 $this->centerY = $this->latToTile($this->lat, $this->zoom); 343 $this->offsetX = floor((floor($this->centerX) - $this->centerX) * $this->tileSize); 344 $this->offsetY = floor((floor($this->centerY) - $this->centerY) * $this->tileSize); 345 } 346 347 /** 348 * 349 * @param float $long 350 * @param int $zoom 351 * @return float 352 */ 353 public function lonToTile(float $long, int $zoom): float 354 { 355 return (($long + 180) / 360) * 2 ** $zoom; 356 } 357 358 /** 359 * 360 * @param float $lat 361 * @param int $zoom 362 * @return float 363 */ 364 public function latToTile(float $lat, int $zoom): float 365 { 366 return (1 - log(tan($lat * M_PI / 180) + 1 / cos($lat * M_PI / 180)) / M_PI) / 2 * 2 ** $zoom; 367 } 368 369 /** 370 * make basemap image. 371 */ 372 public function createBaseMap(): void 373 { 374 $this->image = imagecreatetruecolor($this->width, $this->height); 375 $startX = floor($this->centerX - ($this->width / $this->tileSize) / 2); 376 $startY = floor($this->centerY - ($this->height / $this->tileSize) / 2); 377 $endX = ceil($this->centerX + ($this->width / $this->tileSize) / 2); 378 $endY = ceil($this->centerY + ($this->height / $this->tileSize) / 2); 379 $this->offsetX = -floor(($this->centerX - floor($this->centerX)) * $this->tileSize); 380 $this->offsetY = -floor(($this->centerY - floor($this->centerY)) * $this->tileSize); 381 $this->offsetX += floor($this->width / 2); 382 $this->offsetY += floor($this->height / 2); 383 $this->offsetX += floor($startX - floor($this->centerX)) * $this->tileSize; 384 $this->offsetY += floor($startY - floor($this->centerY)) * $this->tileSize; 385 386 for ($x = $startX; $x <= $endX; $x++) { 387 for ($y = $startY; $y <= $endY; $y++) { 388 $url = str_replace( 389 ['{Z}', '{X}', '{Y}'], 390 [$this->zoom, $x, $y], 391 $this->tileInfo [$this->maptype] ['url'] 392 ); 393 394 $tileData = $this->fetchTile($url); 395 if ($tileData) { 396 $tileImage = imagecreatefromstring($tileData); 397 } 398 if (!$tileData || $tileImage === false || $tileImage === null) { 399 $tileImage = imagecreate($this->tileSize, $this->tileSize); 400 $color = imagecolorallocate($tileImage, 255, 255, 255); 401 @imagestring($tileImage, 1, 127, 127, 'err', $color); 402 } 403 $destX = (int) ($x - $startX) * $this->tileSize + $this->offsetX; 404 $destY = (int) ($y - $startY) * $this->tileSize + $this->offsetY; 405 Logger::debug("imagecopy tile into image: $destX, $destY", $this->tileSize); 406 imagecopy( 407 $this->image, 408 $tileImage, 409 $destX, 410 $destY, 411 0, 412 0, 413 $this->tileSize, 414 $this->tileSize 415 ); 416 } 417 } 418 } 419 420 /** 421 * Fetch a tile (from the source or from the cache) and optionally store it in the cache, 422 * returns false if the tile is not a valid image. 423 * @param string $url 424 * @return bool|string 425 * @todo refactor this to use dokuwiki\HTTP\HTTPClient or dokuwiki\HTTP\DokuHTTPClient 426 * for better proxy handling... 427 */ 428 public function fetchTile(string $url): bool|string 429 { 430 if ($this->useTileCache) { 431 $cached = $this->checkTileCache($url); 432 if ($cached) { 433 return $cached; 434 } 435 } 436 437 $_UA = 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; ' . PHP_OS . ')'; 438 if (function_exists("curl_init")) { 439 // use cUrl 440 $ch = curl_init(); 441 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 442 curl_setopt($ch, CURLOPT_USERAGENT, $_UA); 443 curl_setopt($ch, CURLOPT_REFERER, DOKU_URL); 444 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); 445 curl_setopt($ch, CURLOPT_URL, $url . $this->apikey); 446 Logger::debug("fetchTile: getting: $url using curl_exec"); 447 $tile = curl_exec($ch); 448 curl_close($ch); 449 } else { 450 // use file_get_contents 451 global $conf; 452 $opts = ['http' => [ 453 'method' => "GET", 454 'header' => "Accept-language: en\r\n" . "User-Agent: $_UA\r\n" . "accept: image/png\r\n" . "Referer: " . DOKU_URL . "\r\n", 455 'request_fulluri' => true 456 ]]; 457 if (isset($conf['proxy']['host'], $conf['proxy']['port']) 458 && $conf['proxy']['host'] !== '' 459 && $conf['proxy']['port'] !== '' 460 ) { 461 $opts['http'] += ['proxy' => "tcp://" . $conf['proxy']['host'] . ":" . $conf['proxy']['port']]; 462 } 463 464 $context = stream_context_create($opts); 465 Logger::debug("fetchTile: getting: $url . $this->apikey using file_get_contents and options", $opts); 466 $tile = file_get_contents($url . $this->apikey, false, $context); 467 } 468 469 // check if we retrieved a valid image 470 if (@imagecreatefromstring($tile) !== false) { 471 if ($tile && $this->useTileCache) { 472 $this->writeTileToCache($url, $tile); 473 } 474 return $tile; 475 } 476 return false; 477 } 478 479 /** 480 * 481 * @param string $url 482 * @return string|false 483 */ 484 public function checkTileCache(string $url): string|false 485 { 486 $filename = $this->tileUrlToFilename($url); 487 if (file_exists($filename)) { 488 return file_get_contents($filename); 489 } 490 return false; 491 } 492 493 /** 494 * @param string $url 495 * @return string 496 */ 497 public function tileUrlToFilename(string $url): string 498 { 499 return $this->tileCacheBaseDir . "/" . substr($url, strpos($url, '/') + 1); 500 } 501 502 /** 503 * Write a tile into the cache. 504 * 505 * @param string $url 506 * @param mixed $data 507 */ 508 public function writeTileToCache(string $url, mixed $data): void 509 { 510 $filename = $this->tileUrlToFilename($url); 511 $this->mkdirRecursive(dirname($filename), 0777); 512 file_put_contents($filename, $data); 513 } 514 515 /** 516 * Recursively create the directory. 517 * 518 * @param string $pathname 519 * The directory path. 520 * @param int $mode 521 * File access mode. For more information on modes, read the details on the chmod manpage. 522 */ 523 public function mkdirRecursive(string $pathname, int $mode): bool 524 { 525 if (!is_dir(dirname($pathname))) { 526 $this->mkdirRecursive(dirname($pathname), $mode); 527 } 528 return is_dir($pathname) || mkdir($pathname, $mode) || is_dir($pathname); 529 } 530 531 /** 532 * Place markers on the map and number them in the same order as they are listed in the html. 533 */ 534 public function placeMarkers(): void 535 { 536 $count = 0; 537 $color = imagecolorallocate($this->image, 0, 0, 0); 538 $bgcolor = imagecolorallocate($this->image, 200, 200, 200); 539 $markerBaseDir = __DIR__ . '/icons'; 540 $markerImageOffsetX = 0; 541 $markerImageOffsetY = 0; 542 $markerShadowOffsetX = 0; 543 $markerShadowOffsetY = 0; 544 $markerShadowImg = null; 545 // loop thru marker array 546 foreach ($this->markers as $marker) { 547 // set some local variables 548 $markerLat = $marker ['lat']; 549 $markerLon = $marker ['lon']; 550 $markerType = $marker ['type']; 551 // clear variables from previous loops 552 $markerFilename = ''; 553 $markerShadow = ''; 554 $matches = false; 555 // check for marker type, get settings from markerPrototypes 556 if ($markerType) { 557 foreach ($this->markerPrototypes as $markerPrototype) { 558 if (preg_match($markerPrototype ['regex'], $markerType, $matches)) { 559 $markerFilename = $matches [0] . $markerPrototype ['extension']; 560 if ($markerPrototype ['offsetImage']) { 561 [$markerImageOffsetX, $markerImageOffsetY] = explode( 562 ",", 563 $markerPrototype ['offsetImage'] 564 ); 565 } 566 $markerShadow = $markerPrototype ['shadow']; 567 if ($markerShadow) { 568 [$markerShadowOffsetX, $markerShadowOffsetY] = explode( 569 ",", 570 $markerPrototype ['offsetShadow'] 571 ); 572 } 573 } 574 } 575 } 576 // create img resource 577 if (file_exists($markerBaseDir . '/' . $markerFilename)) { 578 $markerImg = imagecreatefrompng($markerBaseDir . '/' . $markerFilename); 579 } else { 580 $markerImg = imagecreatefrompng($markerBaseDir . '/marker.png'); 581 } 582 // check for shadow + create shadow recource 583 if ($markerShadow && file_exists($markerBaseDir . '/' . $markerShadow)) { 584 $markerShadowImg = imagecreatefrompng($markerBaseDir . '/' . $markerShadow); 585 } 586 // calc position 587 $destX = (int) floor( 588 ($this->width / 2) - 589 $this->tileSize * ($this->centerX - $this->lonToTile($markerLon, $this->zoom)) 590 ); 591 $destY = (int) floor( 592 ($this->height / 2) - 593 $this->tileSize * ($this->centerY - $this->latToTile($markerLat, $this->zoom)) 594 ); 595 // copy shadow on basemap 596 if ($markerShadow && $markerShadowImg) { 597 imagecopy( 598 $this->image, 599 $markerShadowImg, 600 $destX + (int) $markerShadowOffsetX, 601 $destY + (int) $markerShadowOffsetY, 602 0, 603 0, 604 imagesx($markerShadowImg), 605 imagesy($markerShadowImg) 606 ); 607 } 608 // copy marker on basemap above shadow 609 imagecopy( 610 $this->image, 611 $markerImg, 612 $destX + (int) $markerImageOffsetX, 613 $destY + (int) $markerImageOffsetY, 614 0, 615 0, 616 imagesx($markerImg), 617 imagesy($markerImg) 618 ); 619 // add label 620 imagestring( 621 $this->image, 622 3, 623 $destX - imagesx($markerImg) + 1, 624 $destY + (int) $markerImageOffsetY + 1, 625 ++$count, 626 $bgcolor 627 ); 628 imagestring( 629 $this->image, 630 3, 631 $destX - imagesx($markerImg), 632 $destY + (int) $markerImageOffsetY, 633 $count, 634 $color 635 ); 636 } 637 } 638 639 /** 640 * Draw kml trace on the map. 641 * @throws Exception when loading the KML fails 642 */ 643 public function drawKML(): void 644 { 645 // TODO get colour from kml node (not currently supported in geoPHP) 646 $col = imagecolorallocatealpha($this->image, 255, 0, 0, .4 * 127); 647 $kmlgeom = geoPHP::load(file_get_contents($this->kmlFileName), 'kml'); 648 $this->drawGeometry($kmlgeom, $col); 649 } 650 651 /** 652 * Draw geometry or geometry collection on the map. 653 * 654 * @param Geometry $geom 655 * @param int $colour 656 * drawing colour 657 */ 658 private function drawGeometry(Geometry $geom, int $colour): void 659 { 660 if (empty($geom)) { 661 return; 662 } 663 664 switch ($geom->geometryType()) { 665 case 'GeometryCollection': 666 // recursively draw part of the collection 667 for ($i = 1; $i < $geom->numGeometries() + 1; $i++) { 668 $_geom = $geom->geometryN($i); 669 $this->drawGeometry($_geom, $colour); 670 } 671 break; 672 case 'Polygon': 673 $this->drawPolygon($geom, $colour); 674 break; 675 case 'LineString': 676 $this->drawLineString($geom, $colour); 677 break; 678 case 'Point': 679 $this->drawPoint($geom, $colour); 680 break; 681 // TODO implement / do nothing 682 case 'MultiPolygon': 683 case 'MultiLineString': 684 case 'MultiPoint': 685 default: 686 // draw nothing 687 break; 688 } 689 } 690 691 /** 692 * Draw a polygon on the map. 693 * 694 * @param Polygon $polygon 695 * @param int $colour 696 * drawing colour 697 */ 698 private function drawPolygon(Polygon $polygon, int $colour): void 699 { 700 // TODO implementation of drawing holes, 701 // maybe draw the polygon to an in-memory image and use imagecopy, draw polygon in col., draw holes in bgcol? 702 703 // print_r('Polygon:<br />'); 704 // print_r($polygon); 705 $extPoints = []; 706 // extRing is a linestring actually... 707 $extRing = $polygon->exteriorRing(); 708 709 for ($i = 1; $i < $extRing->numGeometries(); $i++) { 710 $p1 = $extRing->geometryN($i); 711 $x = floor( 712 ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom)) 713 ); 714 $y = floor( 715 ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p1->y(), $this->zoom)) 716 ); 717 $extPoints [] = $x; 718 $extPoints [] = $y; 719 } 720 // print_r('points:('.($i-1).')<br />'); 721 // print_r($extPoints); 722 // imagepolygon ($this->image, $extPoints, $i-1, $colour ); 723 imagefilledpolygon($this->image, $extPoints, $i - 1, $colour); 724 } 725 726 /** 727 * Draw a line on the map. 728 * 729 * @param LineString $line 730 * @param int $colour 731 * drawing colour 732 */ 733 private function drawLineString(LineString $line, int $colour): void 734 { 735 imagesetthickness($this->image, 2); 736 for ($p = 1; $p < $line->numGeometries(); $p++) { 737 // get first pair of points 738 $p1 = $line->geometryN($p); 739 $p2 = $line->geometryN($p + 1); 740 // translate to paper space 741 $x1 = floor( 742 ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom)) 743 ); 744 $y1 = floor( 745 ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p1->y(), $this->zoom)) 746 ); 747 $x2 = floor( 748 ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p2->x(), $this->zoom)) 749 ); 750 $y2 = floor( 751 ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p2->y(), $this->zoom)) 752 ); 753 // draw to image 754 imageline($this->image, $x1, $y1, $x2, $y2, $colour); 755 } 756 imagesetthickness($this->image, 1); 757 } 758 759 /** 760 * Draw a point on the map. 761 * 762 * @param Point $point 763 * @param int $colour 764 * drawing colour 765 */ 766 private function drawPoint(Point $point, int $colour): void 767 { 768 imagesetthickness($this->image, 2); 769 // translate to paper space 770 $cx = floor( 771 ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($point->x(), $this->zoom)) 772 ); 773 $cy = floor( 774 ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($point->y(), $this->zoom)) 775 ); 776 $r = 5; 777 // draw to image 778 // imageellipse($this->image, $cx, $cy,$r, $r, $colour); 779 imagefilledellipse($this->image, $cx, $cy, $r, $r, $colour); 780 // don't use imageellipse because the imagesetthickness function has 781 // no effect. So the better workaround is to use imagearc. 782 imagearc($this->image, $cx, $cy, $r, $r, 0, 359, $colour); 783 imagesetthickness($this->image, 1); 784 } 785 786 /** 787 * Draw gpx trace on the map. 788 * @throws Exception when loading the GPX fails 789 */ 790 public function drawGPX(): void 791 { 792 $col = imagecolorallocatealpha($this->image, 0, 0, 255, .4 * 127); 793 $gpxgeom = geoPHP::load(file_get_contents($this->gpxFileName), 'gpx'); 794 $this->drawGeometry($gpxgeom, $col); 795 } 796 797 /** 798 * Draw geojson on the map. 799 * @throws Exception when loading the JSON fails 800 */ 801 public function drawGeojson(): void 802 { 803 $col = imagecolorallocatealpha($this->image, 255, 0, 255, .4 * 127); 804 $gpxgeom = geoPHP::load(file_get_contents($this->geojsonFileName), 'json'); 805 $this->drawGeometry($gpxgeom, $col); 806 } 807 808 /** 809 * add copyright and origin notice and icons to the map. 810 */ 811 public function drawCopyright(): void 812 { 813 $logoBaseDir = __DIR__ . '/' . 'logo/'; 814 $logoImg = imagecreatefrompng($logoBaseDir . $this->tileInfo ['openstreetmap'] ['logo']); 815 $textcolor = imagecolorallocate($this->image, 0, 0, 0); 816 $bgcolor = imagecolorallocate($this->image, 200, 200, 200); 817 818 imagecopy( 819 $this->image, 820 $logoImg, 821 0, 822 imagesy($this->image) - imagesy($logoImg), 823 0, 824 0, 825 imagesx($logoImg), 826 imagesy($logoImg) 827 ); 828 imagestring( 829 $this->image, 830 1, 831 imagesx($logoImg) + 2, 832 imagesy($this->image) - imagesy($logoImg) + 1, 833 $this->tileInfo ['openstreetmap'] ['txt'], 834 $bgcolor 835 ); 836 imagestring( 837 $this->image, 838 1, 839 imagesx($logoImg) + 1, 840 imagesy($this->image) - imagesy($logoImg), 841 $this->tileInfo ['openstreetmap'] ['txt'], 842 $textcolor 843 ); 844 845 // additional tile source info, ie. who created/hosted the tiles 846 $xIconOffset = 0; 847 if ($this->maptype === 'openstreetmap') { 848 $mapAuthor = "(c) OpenStreetMap maps/CC BY-SA"; 849 } else { 850 $mapAuthor = $this->tileInfo [$this->maptype] ['txt']; 851 $iconImg = imagecreatefrompng($logoBaseDir . $this->tileInfo [$this->maptype] ['logo']); 852 $xIconOffset = imagesx($iconImg); 853 imagecopy( 854 $this->image, 855 $iconImg, 856 imagesx($logoImg) + 1, 857 imagesy($this->image) - imagesy($iconImg), 858 0, 859 0, 860 imagesx($iconImg), 861 imagesy($iconImg) 862 ); 863 } 864 imagestring( 865 $this->image, 866 1, 867 imagesx($logoImg) + $xIconOffset + 4, 868 imagesy($this->image) - ceil(imagesy($logoImg) / 2) + 1, 869 $mapAuthor, 870 $bgcolor 871 ); 872 imagestring( 873 $this->image, 874 1, 875 imagesx($logoImg) + $xIconOffset + 3, 876 imagesy($this->image) - ceil(imagesy($logoImg) / 2), 877 $mapAuthor, 878 $textcolor 879 ); 880 } 881} 882