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 instanceof \GdImage) { 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 ( 458 isset($conf['proxy']['host'], $conf['proxy']['port']) 459 && $conf['proxy']['host'] !== '' 460 && $conf['proxy']['port'] !== '' 461 ) { 462 $opts['http'] += ['proxy' => "tcp://" . $conf['proxy']['host'] . ":" . $conf['proxy']['port']]; 463 } 464 465 $context = stream_context_create($opts); 466 Logger::debug("fetchTile: getting: $url . $this->apikey using file_get_contents and options", $opts); 467 $tile = file_get_contents($url . $this->apikey, false, $context); 468 } 469 470 // check if we retrieved a valid image 471 if (@imagecreatefromstring($tile) !== false) { 472 if ($tile && $this->useTileCache) { 473 $this->writeTileToCache($url, $tile); 474 } 475 return $tile; 476 } 477 return false; 478 } 479 480 /** 481 * 482 * @param string $url 483 * @return string|false 484 */ 485 public function checkTileCache(string $url): string|false 486 { 487 $filename = $this->tileUrlToFilename($url); 488 if (file_exists($filename)) { 489 return file_get_contents($filename); 490 } 491 return false; 492 } 493 494 /** 495 * @param string $url 496 * @return string 497 */ 498 public function tileUrlToFilename(string $url): string 499 { 500 return $this->tileCacheBaseDir . "/" . substr($url, strpos($url, '/') + 1); 501 } 502 503 /** 504 * Write a tile into the cache. 505 * 506 * @param string $url 507 * @param mixed $data 508 */ 509 public function writeTileToCache(string $url, mixed $data): void 510 { 511 $filename = $this->tileUrlToFilename($url); 512 $this->mkdirRecursive(dirname($filename), 0777); 513 file_put_contents($filename, $data); 514 } 515 516 /** 517 * Recursively create the directory. 518 * 519 * @param string $pathname 520 * The directory path. 521 * @param int $mode 522 * File access mode. For more information on modes, read the details on the chmod manpage. 523 */ 524 public function mkdirRecursive(string $pathname, int $mode): bool 525 { 526 if (!is_dir(dirname($pathname))) { 527 $this->mkdirRecursive(dirname($pathname), $mode); 528 } 529 return is_dir($pathname) || mkdir($pathname, $mode) || is_dir($pathname); 530 } 531 532 /** 533 * Place markers on the map and number them in the same order as they are listed in the html. 534 */ 535 public function placeMarkers(): void 536 { 537 $count = 0; 538 $color = imagecolorallocate($this->image, 0, 0, 0); 539 $bgcolor = imagecolorallocate($this->image, 200, 200, 200); 540 $markerBaseDir = __DIR__ . '/icons'; 541 $markerImageOffsetX = 0; 542 $markerImageOffsetY = 0; 543 $markerShadowOffsetX = 0; 544 $markerShadowOffsetY = 0; 545 $markerShadowImg = null; 546 // loop thru marker array 547 foreach ($this->markers as $marker) { 548 // set some local variables 549 $markerLat = $marker ['lat']; 550 $markerLon = $marker ['lon']; 551 $markerType = $marker ['type']; 552 // clear variables from previous loops 553 $markerFilename = ''; 554 $markerShadow = ''; 555 $matches = false; 556 // check for marker type, get settings from markerPrototypes 557 if ($markerType) { 558 foreach ($this->markerPrototypes as $markerPrototype) { 559 if (preg_match($markerPrototype ['regex'], $markerType, $matches)) { 560 $markerFilename = $matches [0] . $markerPrototype ['extension']; 561 if ($markerPrototype ['offsetImage']) { 562 [$markerImageOffsetX, $markerImageOffsetY] = explode( 563 ",", 564 $markerPrototype ['offsetImage'] 565 ); 566 } 567 $markerShadow = $markerPrototype ['shadow']; 568 if ($markerShadow) { 569 [$markerShadowOffsetX, $markerShadowOffsetY] = explode( 570 ",", 571 $markerPrototype ['offsetShadow'] 572 ); 573 } 574 } 575 } 576 } 577 // create img resource 578 if (file_exists($markerBaseDir . '/' . $markerFilename)) { 579 $markerImg = imagecreatefrompng($markerBaseDir . '/' . $markerFilename); 580 } else { 581 $markerImg = imagecreatefrompng($markerBaseDir . '/marker.png'); 582 } 583 // check for shadow + create shadow recource 584 if ($markerShadow && file_exists($markerBaseDir . '/' . $markerShadow)) { 585 $markerShadowImg = imagecreatefrompng($markerBaseDir . '/' . $markerShadow); 586 } 587 // calc position 588 $destX = (int) floor( 589 ($this->width / 2) - 590 $this->tileSize * ($this->centerX - $this->lonToTile($markerLon, $this->zoom)) 591 ); 592 $destY = (int) floor( 593 ($this->height / 2) - 594 $this->tileSize * ($this->centerY - $this->latToTile($markerLat, $this->zoom)) 595 ); 596 // copy shadow on basemap 597 if ($markerShadow && $markerShadowImg) { 598 imagecopy( 599 $this->image, 600 $markerShadowImg, 601 $destX + (int) $markerShadowOffsetX, 602 $destY + (int) $markerShadowOffsetY, 603 0, 604 0, 605 imagesx($markerShadowImg), 606 imagesy($markerShadowImg) 607 ); 608 } 609 // copy marker on basemap above shadow 610 imagecopy( 611 $this->image, 612 $markerImg, 613 $destX + (int) $markerImageOffsetX, 614 $destY + (int) $markerImageOffsetY, 615 0, 616 0, 617 imagesx($markerImg), 618 imagesy($markerImg) 619 ); 620 // add label 621 imagestring( 622 $this->image, 623 3, 624 $destX - imagesx($markerImg) + 1, 625 $destY + (int) $markerImageOffsetY + 1, 626 ++$count, 627 $bgcolor 628 ); 629 imagestring( 630 $this->image, 631 3, 632 $destX - imagesx($markerImg), 633 $destY + (int) $markerImageOffsetY, 634 $count, 635 $color 636 ); 637 } 638 } 639 640 /** 641 * Draw kml trace on the map. 642 * @throws Exception when loading the KML fails 643 */ 644 public function drawKML(): void 645 { 646 // TODO get colour from kml node (not currently supported in geoPHP) 647 $col = imagecolorallocatealpha($this->image, 255, 0, 0, .4 * 127); 648 $kmlgeom = geoPHP::load(file_get_contents($this->kmlFileName), 'kml'); 649 $this->drawGeometry($kmlgeom, $col); 650 } 651 652 /** 653 * Draw geometry or geometry collection on the map. 654 * 655 * @param Geometry $geom 656 * @param int $colour 657 * drawing colour 658 */ 659 private function drawGeometry(Geometry $geom, int $colour): void 660 { 661 if (empty($geom)) { 662 return; 663 } 664 665 switch ($geom->geometryType()) { 666 case 'GeometryCollection': 667 // recursively draw part of the collection 668 for ($i = 1; $i < $geom->numGeometries() + 1; $i++) { 669 $_geom = $geom->geometryN($i); 670 $this->drawGeometry($_geom, $colour); 671 } 672 break; 673 case 'Polygon': 674 $this->drawPolygon($geom, $colour); 675 break; 676 case 'LineString': 677 $this->drawLineString($geom, $colour); 678 break; 679 case 'Point': 680 $this->drawPoint($geom, $colour); 681 break; 682 // TODO implement / do nothing 683 case 'MultiPolygon': 684 case 'MultiLineString': 685 case 'MultiPoint': 686 default: 687 // draw nothing 688 break; 689 } 690 } 691 692 /** 693 * Draw a polygon on the map. 694 * 695 * @param Polygon $polygon 696 * @param int $colour 697 * drawing colour 698 */ 699 private function drawPolygon(Polygon $polygon, int $colour): void 700 { 701 // TODO implementation of drawing holes, 702 // maybe draw the polygon to an in-memory image and use imagecopy, draw polygon in col., draw holes in bgcol? 703 704 // print_r('Polygon:<br />'); 705 // print_r($polygon); 706 $extPoints = []; 707 // extRing is a linestring actually... 708 $extRing = $polygon->exteriorRing(); 709 710 for ($i = 1; $i < $extRing->numGeometries(); $i++) { 711 $p1 = $extRing->geometryN($i); 712 $x = floor( 713 ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom)) 714 ); 715 $y = floor( 716 ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p1->y(), $this->zoom)) 717 ); 718 $extPoints [] = $x; 719 $extPoints [] = $y; 720 } 721 // print_r('points:('.($i-1).')<br />'); 722 // print_r($extPoints); 723 // imagepolygon ($this->image, $extPoints, $i-1, $colour ); 724 imagefilledpolygon($this->image, $extPoints, $i - 1, $colour); 725 } 726 727 /** 728 * Draw a line on the map. 729 * 730 * @param LineString $line 731 * @param int $colour 732 * drawing colour 733 */ 734 private function drawLineString(LineString $line, int $colour): void 735 { 736 imagesetthickness($this->image, 2); 737 for ($p = 1; $p < $line->numGeometries(); $p++) { 738 // get first pair of points 739 $p1 = $line->geometryN($p); 740 $p2 = $line->geometryN($p + 1); 741 // translate to paper space 742 $x1 = floor( 743 ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom)) 744 ); 745 $y1 = floor( 746 ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p1->y(), $this->zoom)) 747 ); 748 $x2 = floor( 749 ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p2->x(), $this->zoom)) 750 ); 751 $y2 = floor( 752 ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p2->y(), $this->zoom)) 753 ); 754 // draw to image 755 imageline($this->image, $x1, $y1, $x2, $y2, $colour); 756 } 757 imagesetthickness($this->image, 1); 758 } 759 760 /** 761 * Draw a point on the map. 762 * 763 * @param Point $point 764 * @param int $colour 765 * drawing colour 766 */ 767 private function drawPoint(Point $point, int $colour): void 768 { 769 imagesetthickness($this->image, 2); 770 // translate to paper space 771 $cx = floor( 772 ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($point->x(), $this->zoom)) 773 ); 774 $cy = floor( 775 ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($point->y(), $this->zoom)) 776 ); 777 $r = 5; 778 // draw to image 779 // imageellipse($this->image, $cx, $cy,$r, $r, $colour); 780 imagefilledellipse($this->image, $cx, $cy, $r, $r, $colour); 781 // don't use imageellipse because the imagesetthickness function has 782 // no effect. So the better workaround is to use imagearc. 783 imagearc($this->image, $cx, $cy, $r, $r, 0, 359, $colour); 784 imagesetthickness($this->image, 1); 785 } 786 787 /** 788 * Draw gpx trace on the map. 789 * @throws Exception when loading the GPX fails 790 */ 791 public function drawGPX(): void 792 { 793 $col = imagecolorallocatealpha($this->image, 0, 0, 255, .4 * 127); 794 $gpxgeom = geoPHP::load(file_get_contents($this->gpxFileName), 'gpx'); 795 $this->drawGeometry($gpxgeom, $col); 796 } 797 798 /** 799 * Draw geojson on the map. 800 * @throws Exception when loading the JSON fails 801 */ 802 public function drawGeojson(): void 803 { 804 $col = imagecolorallocatealpha($this->image, 255, 0, 255, .4 * 127); 805 $gpxgeom = geoPHP::load(file_get_contents($this->geojsonFileName), 'json'); 806 $this->drawGeometry($gpxgeom, $col); 807 } 808 809 /** 810 * add copyright and origin notice and icons to the map. 811 */ 812 public function drawCopyright(): void 813 { 814 $logoBaseDir = __DIR__ . '/' . 'logo/'; 815 $logoImg = imagecreatefrompng($logoBaseDir . $this->tileInfo ['openstreetmap'] ['logo']); 816 $textcolor = imagecolorallocate($this->image, 0, 0, 0); 817 $bgcolor = imagecolorallocate($this->image, 200, 200, 200); 818 819 imagecopy( 820 $this->image, 821 $logoImg, 822 0, 823 imagesy($this->image) - imagesy($logoImg), 824 0, 825 0, 826 imagesx($logoImg), 827 imagesy($logoImg) 828 ); 829 imagestring( 830 $this->image, 831 1, 832 imagesx($logoImg) + 2, 833 imagesy($this->image) - imagesy($logoImg) + 1, 834 $this->tileInfo ['openstreetmap'] ['txt'], 835 $bgcolor 836 ); 837 imagestring( 838 $this->image, 839 1, 840 imagesx($logoImg) + 1, 841 imagesy($this->image) - imagesy($logoImg), 842 $this->tileInfo ['openstreetmap'] ['txt'], 843 $textcolor 844 ); 845 846 // additional tile source info, ie. who created/hosted the tiles 847 $xIconOffset = 0; 848 if ($this->maptype === 'openstreetmap') { 849 $mapAuthor = "(c) OpenStreetMap maps/CC BY-SA"; 850 } else { 851 $mapAuthor = $this->tileInfo [$this->maptype] ['txt']; 852 $iconImg = imagecreatefrompng($logoBaseDir . $this->tileInfo [$this->maptype] ['logo']); 853 $xIconOffset = imagesx($iconImg); 854 imagecopy( 855 $this->image, 856 $iconImg, 857 imagesx($logoImg) + 1, 858 imagesy($this->image) - imagesy($iconImg), 859 0, 860 0, 861 imagesx($iconImg), 862 imagesy($iconImg) 863 ); 864 } 865 imagestring( 866 $this->image, 867 1, 868 imagesx($logoImg) + $xIconOffset + 4, 869 imagesy($this->image) - ceil(imagesy($logoImg) / 2) + 1, 870 $mapAuthor, 871 $bgcolor 872 ); 873 imagestring( 874 $this->image, 875 1, 876 imagesx($logoImg) + $xIconOffset + 3, 877 imagesy($this->image) - ceil(imagesy($logoImg) / 2), 878 $mapAuthor, 879 $textcolor 880 ); 881 } 882} 883