-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstaticmap.php
958 lines (888 loc) · 41.5 KB
/
staticmap.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
<?php
/**
* staticMapLite 0.02
*
* Copyright 2009 Gerhard Koch
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Gerhard Koch <gerhard.koch AT ymail.com>
*/
/*error_reporting(0);
ini_set('display_errors','off');
*/
require 'config.php';
require 'marker.php';
require 'linestring.php';
/**
* implementation of the staticMap
*/
Class staticMapLite extends configuredStaticMap {
/** Whether fit_to_content=1 was set */
protected $fitToContentRequested = false;
/** zoom level of the map */
protected $zoom = -1;
/** latitude of the center of the map */
protected $lat;
/** longitude of the center of the map */
protected $lon;
/** width of the map */
protected $width = 0;
/** height of the map */
protected $height = 0;
/** markers to be added to the map */
protected $markers;
/** lines/areas to be added to the map */
protected $lines = array();
/** circles and pies to be added to the map */
protected $arcs = array();
/** the map image */
protected $image;
/** base map style to be used */
protected $maptype;
protected $centerX, $centerY, $offsetX, $offsetY;
/** size of the tiles of the basemap */
protected $tileSize = 0;
/** API key used to retrieve tiles from the tile server */
protected $apiKey = '';
/** MD5 sum of the query parameters, used as key in the map cache */
protected $mapCacheID = '';
protected $mapCacheFile = '';
protected $mapCacheExtension = 'png';
/**
* Shold the image not be written to the map cache.
* This property will be set to true if the retrieval of a tile fails and
* no useful image could be produced.
*/
protected $doNotWriteMapCache = false;
/**
* HTTP status code to use for the response.
*/
protected $statusCode = 200;
/** minimum longitude of things to draw on the map */
private $minLon = 180;
/** maximum longitude of things to draw on the map */
private $maxLon = -180;
/** minimum latitude of things to draw on the map */
private $minLat = 90;
/** maximum latitude of things to draw on the map */
private $maxLat = -90;
/** buffer required for markers on the left side */
private $markerBufferLeft = 0;
/** buffer required for markers on the right side */
private $markerBufferRight = 0;
/** buffer required for markers on the bottom side */
private $markerBufferBottom = 0;
/** buffer required for markers on the top side */
private $markerBufferTop = 0;
public function __construct(){
$this->width = $this->maxSize;
$this->height = $this->maxSize;
$this->markers = array();
$this->lines = array();
$this->maptype = $this->tileDefaultSrc;
}
/**
* Explode string at commas like explode() but with respect for escaped commas.
*/
private function explodeWithEsc($input) {
$len = strlen($input);
$result = array();
$current = '';
for ($i = 0; $i < $len; $i++) {
if ($i > 0 && $input[$i] === ',' && $input[$i - 1] != '\\') {
array_push($result, $current);
$current = '';
} else if ($i > 0 && $input[$i] === ',' && $input[$i - 1] === '\\') {
$current = $current . ',';
} else if ($i === 0 && $input[$i] === ',') {
array_push($result, '');
$current = '';
} else if ($i > 0 && $input[$i] === '\\' && $input[$i - 1] == '\\') {
$current = $current . '\\';
} else {
$current = $current . $input[$i];
}
}
if (strlen($current)) array_push($result, $current);
return $result;
}
/**
* Parse parameters (query string)
*/
public function parseParams(){
global $_REQUEST;
$parameters = $_REQUEST;
if ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'POST') {
output_error('GET and POST requests are supported only.', 405);
}
$this->fitToContentRequested = (!array_key_exists('zoom', $_REQUEST) && !array_key_exists('center', $_REQUEST));
// get zoom from GET paramter
if (isset($parameters['zoom'])) {
$zoom = $parameters['zoom'];
if (ctype_digit($zoom)) {
$this->zoom = intval($parameters['zoom']);
} else {
output_error('zoom needs to be a positive integer');
}
} else if (!$this->fitToContentRequested) {
output_error('Please provide any of the following parameters: \'zoom\', \'path\', \'markers\'.');
}
if ($this->zoom > 19) $this->zoom = 19;
// get lat and lon from GET paramter
if (isset($parameters['center'])) {
$center = explode(',', $parameters['center']);
if (count($center) != 2 || !is_numeric($center[0]) || !is_numeric($center[1])) {
output_error('The center parameter must have the following form: latitude,longitude. Both parts have to be floats.');
}
$this->lat = floatval($center[0]);
$this->lon = floatval($center[1]);
} else if (!$this->fitToContentRequested) {
output_error('Parameter \'center\' is missing.');
}
// get width and height from GET paramters
if (isset($parameters['size'])) {
$size = explode('x', $parameters['size']);
if (count($size) != 2 || !ctype_digit($size[0]) || !ctype_digit($size[1])) {
output_error('The size paramter must have the following form: <integer>x<integer>. The first integer is the width, the second the height in pixel.');
}
$this->width = intval($size[0]);
$this->height = intval($size[1]);
if ($this->width <= 0 || $this->height <= 0) {
output_error('Width and height must be positive integers.');
}
} else if (!$this->fitToContentRequested) {
$this->width = 500;
$this->height = 350;
} else {
output_error('The size parameter is missing.');
}
if ($this->width > $this->maxSize || $this->height > $this->maxSize) {
output_error('The requested map image exceeds the maximum size of ' . $this->maxSize . ' pixels for map images.', 413);
}
// markers parameter
if(isset($parameters['markers'])){
$nextMarkerLabel = 1;
// split up into markers
$markers = preg_split('/%7C|\|/',$parameters['markers']);
foreach($markers as $marker){
// build array of keys and values
$params = array();
// First check if the marker definition contains a comma.
// If it does not, it is the legacy version which we support here.
$colon_pos = strpos($marker, ':', 1);
if (!$colon_pos or $colon_pos >= strlen($marker) - 1) {
// No colon in the string and the colon is not used as label character.
// This is parsing of the legacy syntax.
$parts = explode(',', $marker);
if (count($parts) < 3) {
output_error('The marker definition was interpreted using the legacy syntax but it contained less than 4 elements for one or multiple markers.');
}
$params['lat'] = $parts[0];
$params['lon'] = $parts[1];
$params['image'] = $parts[2];
if (count($parts) > 3) {
$params['label'] = $parts[3];
}
} else {
// New syntax.
// split up by , into key:value pairs
$kvPairs = $this->explodeWithEsc($marker);
foreach($kvPairs as $pair) {
list($key, $value) = explode(':', $pair, 2);
$params[trim($key)] = trim($value);
}
}
// parse parameters lat, lon and image – they are mandatory
if (isset($params['lat']) && isset($params['lon']) && isset($params['image'])) {
$markerLat = floatval($params['lat']);
$markerLon = floatval($params['lon']);
$markerImage = basename($params['image']);
$markerColor = new Color(255, 0, 0, 255);
// parse color
if (isset($params['color'])) {
$markerColor = Color::colorFromHex($params['color']);
}
$fontColor = new Color(0, 0, 0, 255);
if (isset($params['fontcolor'])) {
$fontColor = Color::colorFromHex($params['fontcolor']);
}
// parse parameter label or use index of the marker if label is not set
$markerLabel = (string)$nextMarkerLabel;
if (isset($params['label'])) {
if (strlen($params['label']) > 1) {
output_error('Labels of markers must be zero or one character long.');
}
$markerLabel = $params['label'];
} else {
if ($nextMarkerLabel++ > 9) {
output_error('More than 9 unlabelled markers.');
}
}
// marker popup
$markerPopup = null;
if (isset($params['popup'])) {
$markerPopup = $params['popup'];
}
// marker popup
$popupFontSize = 10;
if (isset($params['popupsize'])) {
$popupFontSize = floatval($params['popupsize']);
}
// label font
$font = null;
if (isset($params['font'])) {
$font = $params['font'];
if (!is_readable($this->fontBaseDir . $font . '.ttf')) {
output_error('Font ' . $font . ' is not available. Please provide a ' .
'font which accessiable for the staticmap API.');
}
}
// popup font
$fontPopup = null;
if (isset($params['popupfont'])) {
$fontPopup = $params['popupfont'];
if (!is_readable($this->fontBaseDir . $fontPopup . '.ttf')) {
output_error('Font ' . $fontPopup . ' is not available. Please provide a ' .
'font which accessiable for the staticmap API.');
}
}
$lineHeight = 1.2 * $popupFontSize;
if (isset($params['lineheight'])) {
$lineHeight = floatval($params['lineheight']);
}
if ($fontPopup == null) {
$fontPopup = $font;
}
$this->markers[] = new Marker($markerLat, $markerLon, $markerImage,
$markerColor, $fontColor, $markerLabel, $markerPopup, $font, $fontPopup, $popupFontSize,
$lineHeight);
} else {
output_error('One of the mandatory marker arguments is missing: lat, lon, ' .
'image');
}
}
}
// path, circles and pies parameter
foreach (array('path', 'circle', 'pie') as $paramName) {
if (isset($parameters[$paramName])) {
$this->parsePathCircleParam($parameters, $paramName);
}
}
// maptype parameter
if(array_key_exists('maptype', $parameters)) {
$this->maptype = $parameters['maptype'];
}
if (count($this->tileSources) == 0) {
output_error('No map sources are defined, a map could not be rendered for you. Please contact the administrator of this service.');
}
if(array_key_exists($this->maptype, $this->tileSources)) {
$this->tileSrcUrl = $this->tileSources[$this->maptype]['url'];
$this->tileSize = $this->tileSources[$this->maptype]['tileSize'];
// If useTileCache is set for this source, overwrite global setting.
if (array_key_exists('useTileCache', $this->tileSources[$this->maptype])) {
$this->useTileCache = $this->tileSources[$this->maptype]['useTileCache'];
}
} else {
output_error('Unknown maptype ' . $this->maptype);
}
if (count($this->markers) === 0 && count($this->lines) === 0 && count($this->arcs) === 0 && $this->fitToContentRequested) {
output_error('The parameters size and zoom need to be set if neither path nor markers, circles or pies are provided.');
}
if ($this->fitToContentRequested) {
$this->fitToContent();
}
// mapcache parameter
if(isset($parameters['nocache']) && !$this->ignoreNoCacheProperty){
$this->doNotReadMapCache = true;
}
// attribution parameter
if(isset($parameters['attribution'])) {
if ($parameters['attribution'] == 'false'){
$this->attribution = false;
} else if ($parameters['attribution'] != 'true') {
output_error('Illegal option for parameter \'attribution\'');
}
}
// attribution-font parameter
if (isset($parameters['attribution-font'])) {
$this->attributionFont = $parameters['attribution-font'];
if (strlen($this->attributionFont) == 0) {
output_error('Missing font name for attribution text.');
}
if (!is_readable($this->fontBaseDir . $this->attributionFont . '.ttf')) {
output_error('Font ' . $font . ' is not available. Please provide a font which ' .
'accessiable for the staticmap API.');
}
}
// parse API key
$this->apiKey = $this->getApiKey();
}
protected function parsePathCircleParam($parameters, $paramName) {
// split up into single paths
$elements = preg_split('/%7C|\|/', $parameters[$paramName]);
foreach ($elements as $elem) {
// split up by , into key:value pairs
$kvPairs = explode(',', $elem);
$params = array();
foreach ($kvPairs as $pair) {
list($key, $value) = explode(':', $pair, 2);
$params[trim($key)] = trim($value);
}
if ($paramName === 'path' && !isset($params['points'])) {
output_error('Mandatory argument points for path is missing.');
}
if (($paramName === 'circle' || $paramName === 'pie') && !isset($params['center'])) {
output_error('Mandatory argument center for circle or pie is missing.');
}
if (($paramName === 'circle' || $paramName === 'pie') && !isset($params['radius'])) {
output_error('Mandatory argument radius for circle or pie is missing.');
}
if ($paramName === 'pie' && (!isset($params['from']) || !isset($params['to']))) {
output_error('Mandatory argument "from" or "to" for pie is missing.');
}
$lineColor = new Color(255, 0, 0, 255);
if (isset($params['color'])) {
$lineColor = Color::colorFromHex($params['color']);
}
$fillColor = new Color(255, 255, 0, 255);
if (isset($params['fillcolor'])) {
$fillColor = Color::colorFromHex($params['fillcolor']);
}
$lineWidth = 3;
if (isset($params['width']) && is_numeric($params['width'])) {
$lineWidth = intVal($params['width']);
}
$from = 0;
$to = 360;
if ($paramName === 'path') {
$ls = buildLineString($params['points'], $lineColor, $lineWidth, $fillColor);
array_push($this->lines, $ls);
} elseif ($paramName === 'circle' || $paramName === 'pie') {
$straightEdges = TRUE;
if ($paramName === 'pie') {
$start = $params['from'];
$end = $params['to'];
if ($start >= $end) {
output_error('End angle has to be larger than start angle');
}
// convert angles to clockwise as preferred by libgd
$from = 360 - $end;
$to = ($end - $start) + $from;
if (isset($params['straight_edges'])) {
$straightEdges = Arc::urlParamToBool($params['straight_edges']);
}
}
$radius = $params['radius'];
if (!is_numeric($radius) || $radius <= 0) {
output_error('Radius is not a number or smaller or equal than 0.');
}
$centerRaw = $params['center'];
if ($centerRaw[0] != '(' || $centerRaw[strlen($centerRaw) - 1] != ')') {
output_error('Center coordinate specification is invalid. Its first character must be an opening round bracket, the last one must be a closing round bracket.');
}
list($lon, $lat) = explode(' ', substr($centerRaw, 1, strlen($centerRaw) - 2), 2);
if (is_numeric($lon) && is_numeric($lat)) {
$center = new Point($lon, $lat);
array_push($this->arcs, new Arc($center, $radius, $lineWidth, $lineColor, $fillColor, $from, $to, $straightEdges));
} else {
output_error('A center coordinate of a pie or circle is not a number.');
}
}
}
}
/**
* Calculate width, height and zoom level in order that all markers, lines and polygons fit onto the map.
*/
public function fitToContent() {
if (count($this->markers) == 0 && count($this->lines) == 0 && count($this->arcs) == 0) {
output_error('Failed to fit map to content because the map has no markers, lines or polygons');
}
// Get bounding box of all markers
foreach ($this->markers as $marker) {
$this->updateBounds($marker->lon, $marker->lat);
// Get width of marker images
$markerPath = $this->maptype. '/'. $marker->image;
$markerLookupResult = null;
if (isset($this->markerLookup[$markerPath])) {
$markerLookupResult = $this->markerLookup[$this->maptype.'/'.$marker->image];
}
if (!$markerLookupResult) {
output_error('Marker type \'' . $marker->image . '\' is not available on this instance of GfStaticMap.');
}
$markerImg = imagecreatefrompng($this->getMarkerPath($markerLookupResult['filename']));
if (!$markerImg) {
output_error('Marker type \'' . $marker->image . '\' is not available. Marker image is broken or missing.');
}
$markerWidth = imagesx($markerImg);
$markerHeight = imagesy($markerImg);
$hotX = $markerLookupResult['hotx'];
$hotY = $markerLookupResult['hoty'];
$this->markerBufferLeft = max($this->markerBufferLeft, $hotX);
$this->markerBufferRight = max($this->markerBufferRight, $markerWidth - $hotY);
$this->markerBufferBottom = max($this->markerBufferBottom, $hotY);
$this->markerBufferTop = max($this->markerBufferTop, $markerHeight - $hotY);
}
foreach ($this->lines as $line) {
for ($i = 0; $i < $line->length(); $i++) {
$this->updateBounds($line->at($i)->x, $line->at($i)->y);
$this->markerBufferLeft = max($this->markerBufferLeft, $line->width);
$this->markerBufferRight = max($this->markerBufferRight, $line->width);
$this->markerBufferBottom = max($this->markerBufferBottom, $line->width);
$this->markerBufferTop = max($this->markerBufferTop, $line->width);
}
}
$earth_radius = 6378137.0;
foreach ($this->arcs as $arc) {
// Get northern point of circle
$radius = $arc->radius;
$latNorth = (180 * $radius) / ($earth_radius * pi()) + $arc->center->y;
$this->updateBounds($arc->center->x, $latNorth);
$latSouth = $arc->center->y - (180 * $radius) / ($earth_radius * pi());
$this->updateBounds($arc->center->x, $latSouth);
$lonEast = $arc->center->x + ($radius * 180) / (pi() * $earth_radius * cos(deg2rad($arc->center->y)));
$lonWest = $arc->center->x - ($lonEast - $arc->center->x);
$this->updateBounds($lonWest, $arc->center->y);
$this->updateBounds($lonEast, $arc->center->y);
}
$this->lon = ($this->maxLon - $this->minLon) / 2 + $this->minLon;
$this->lat = ($this->maxLat - $this->minLat) / 2 + $this->minLat;
// get maximum zoom level for given maximum map size
$this->zoom = 19;
for (; $this->zoom >= 0; $this->zoom--) {
$minX = lonToTile($this->minLon, $this->zoom); // - $this->markerBufferLeft / $this->tileSize;
$minY = latToTile($this->maxLat, $this->zoom); // - $this->markerBufferTop / $this->tileSize;
$maxX = lonToTile($this->maxLon, $this->zoom); // + $this->markerBufferRight / $this->tileSize;
$maxY = latToTile($this->minLat, $this->zoom); // + $this->markerBufferBottom / $this->tileSize;
if ((($maxX - $minX) * $this->tileSize <= $this->width)
&& (($maxY - $minY) * $this->tileSize <= $this->height)) {
break;
}
}
}
protected function updateBounds($lon, $lat) {
if ($lon < $this->minLon) {
$this->minLon = $lon;
}
if ($lon > $this->maxLon) {
$this->maxLon = $lon;
}
if ($lat < $this->minLat) {
$this->minLat = $lat;
}
if ($lat > $this->maxLat) {
$this->maxLat = $lat;
}
}
public function initCoords(){
$this->centerX = lonToTile($this->lon, ($this->zoom));
$this->centerY = latToTile($this->lat, ($this->zoom));
$this->offsetX = floor((floor($this->centerX)-$this->centerX)*$this->tileSize);
$this->offsetY = floor((floor($this->centerY)-$this->centerY)*$this->tileSize);
}
/**
* Create the base map (fetching tiles and placing them at the correct locations)
*/
public function createBaseMap(){
$this->image = imagecreatetruecolor($this->width, $this->height);
// Allow to leave the image partially transparent if it exceeds the Web Mercator
// definition area towards north/south.
imagealphablending($this->image, FALSE);
imagesavealpha($this->image, TRUE);
$startX = floor($this->centerX-($this->width/$this->tileSize)/2);
$startY = floor($this->centerY-($this->height/$this->tileSize)/2);
$endX = ceil($this->centerX+($this->width/$this->tileSize)/2);
$endY = ceil($this->centerY+($this->height/$this->tileSize)/2);
$this->offsetX = -floor(($this->centerX-floor($this->centerX))*$this->tileSize);
$this->offsetY = -floor(($this->centerY-floor($this->centerY))*$this->tileSize);
$this->offsetX += floor($this->width/2);
$this->offsetY += floor($this->height/2);
$this->offsetX += floor($startX-floor($this->centerX))*$this->tileSize;
$this->offsetY += floor($startY-floor($this->centerY))*$this->tileSize;
$xTiles = $endX - $startX + 1;
$yTiles = $endY - $startY + 1;
if ($xTiles * $yTiles > $this->maxTileCount && $this->maxTileCount > 0) {
output_error('The map you requested covers too much tiles. A map'
. ' must only cover ' . $this->maxTileCount . ' tiles.', 413);
}
$added_tile = false;
for($x=$startX; $x<=$endX; $x++){
// normalise x index
$xNorm = $x % (2 ** $this->zoom);
for($y=$startY; $y<=$endY; $y++){
$destX = ($x-$startX)*$this->tileSize+$this->offsetX;
$destY = ($y-$startY)*$this->tileSize+$this->offsetY;
// skip this tile if it is too far in the north or south
if ($y < 0 || $y >= (2 ** $this->zoom)) {
// Make the area transparent.
imagefilledrectangle($this->image, $destX, $destY, $destX + $this->tileSize, $destY + $this->tileSize, 0xff000000);
continue;
}
$url = str_replace(array('{P}', '{Z}','{X}','{Y}'),array($this->apiKey, $this->zoom,
$xNorm, $y), $this->tileSrcUrl);
try {
$tileData = $this->fetchTile($url);
$tileImage = imagecreatefromstring($tileData);
} catch (Exception $ex) {
error_log('Tile request exception: ' . $ex->getMessage());
output_error($this->tileFetchFailureMessage, $this->statusCode);
}
imagecopy($this->image, $tileImage, $destX, $destY, 0, 0, $this->tileSize,
$this->tileSize);
$added_tile = true;
}
}
if (!$added_tile) {
error_log('Background map composition error: No tiles found within the requested bounding box.');
output_error('Failed to build your map image. No tiles of the background map found within the requested bounding box.');
}
// Enable alpha blending now because we want to add the attribution
imagealphablending($this->image, TRUE);
}
/**
* Create an image which contains marker or a colorized marker mask.
*
* This method does not add the marker to the map image.
*
* @param markerFilename path to the marker
*
* @param markerLookupResult marker returned from $this->markerLookup array
*
* @param colorize Is the image to be added a mask to be colorized?
*
* @param marker array with the parameters describing the marker
*
* @return array with the X coordinate of the upper left corner as first
* element and the Y coordinate of the upper left corner as second element.
*/
protected function addMarkerOrMask($markerFilename, $markerLookupResult, $colorize, $marker) {
if (!file_exists($markerFilename)) return;
$markerImg = imagecreatefrompng($markerFilename);
$destX = floor(($this->width/2)-$this->tileSize*($this->centerX - lonToTile($marker->lon,
$this->zoom)));
$destY = floor(($this->height/2)-$this->tileSize*($this->centerY -
latToTile($marker->lat, $this->zoom)));
$destY = $destY - $markerLookupResult['hoty'];
$destX = $destX - $markerLookupResult['hotx'];
// fill all black pixels of the image with the color of the marker
if ($colorize) {
imagefilter($markerImg, IMG_FILTER_COLORIZE, $marker->color->red, $marker->color->green,
$marker->color->blue);
}
// add the marker to the map image
imagecopy($this->image, $markerImg, $destX, $destY, 0, 0, imagesx($markerImg),
imagesy($markerImg)); return array($destX, $destY);
return array($destX, $destY);
}
protected function getMarkerPath($filename) {
return $this->markerBaseDir. '/' . $filename;
}
/**
* Render the markers on the map.
*/
public function placeMarkers() {
foreach($this->markers as $marker){
$markerLat = $marker->lat;
$markerLon = $marker->lon;
$markerImage = $marker->image;
// retrieve the marker details from the array of the available marker icons
$mlu = $this->markerLookup[$this->maptype.'/'.$marker->image] ?? FALSE;
if (!$mlu) {
output_error('Marker type \'' . $marker->image . '\' is not available on this instance of GfStaticMap.');
}
$markerFilename = $this->getMarkerPath($mlu['filename']);
$markerMaskname = $this->getMarkerPath($mlu['maskname']);
list($destX, $destY) = $this->addMarkerOrMask($markerMaskname, $mlu, true, $marker);
$this->addMarkerOrMask($markerFilename, $mlu, false, $marker);
// determine label width
$marker->setAbsFontPaths($this->fontBaseDir, $mlu['font']);
$size = imagettfbbox($mlu['textsize'], 0, $marker->font, $marker->label);
$width = $size[4] - $size[0];
// place label (1st marker=1 etc)
$fontColor = $marker->fontColor->allocateForFontNoAlpha($this->image);
imagettftext($this->image, $mlu['textsize'], 0, $destX + $mlu['textx'] - $width/2,
$destY + $mlu['texty'], $fontColor, $marker->font, $marker->label);
$marker->placePopupBox($this->image, $destX + $mlu['width'] / 2, $destY);
};
}
/**
* Render the lines/polygons on the map.
*/
public function placeLines() {
foreach($this->lines as $line) {
// build array of points transformed to pixel coordinates
list($gdPArray, $numPoints) = $line->gdPointsArray($this->width, $this->height,
$this->centerX, $this->centerY, $this->zoom, $this->tileSize);
if (!($line->fillColor->isTransparent()) && $line->isClosed()) {
imagefilledpolygon($this->image, $gdPArray, $numPoints,
$line->fillColor->allocate($this->image));
}
}
foreach($this->lines as $line) {
for ($i = 0; $i < $line->length() - 1; $i++) {
imagesetthickness($this->image, $line->width);
imageline(
$this->image,
$line->at($i)->x_on_map($this->width, $this->centerX, $this->tileSize, $this->zoom),
$line->at($i)->y_on_map($this->height, $this->centerY, $this->tileSize, $this->zoom),
$line->at($i + 1)->x_on_map($this->width, $this->centerX, $this->tileSize, $this->zoom),
$line->at($i + 1)->y_on_map($this->height, $this->centerY, $this->tileSize, $this->zoom),
$line->lineColor->allocate($this->image)
);
}
}
}
/**
* Render the circles and pies on the map.
*/
public function placeArcs() {
// Arcs have to be drawn on a separate image due to a bug in GD.
// If two semi-transparent arcs are drawn, the second one gets less transparent than the first one and specified.
// By drawing on an empty image and copying that onto the destination image, we can solve the issue.
$arcsImage = imagecreatetruecolor($this->width, $this->height);
imagealphablending($arcsImage, false);
$blank = imagecolorallocatealpha($arcsImage, 0, 0, 0, 127.0);
imagefill($arcsImage, 0, 0, $blank);
imagesavealpha($arcsImage, true);
foreach($this->arcs as $arc) {
$centerX = $arc->center->x_on_map($this->width, $this->centerX, $this->tileSize, $this->zoom);
$centerY = $arc->center->y_on_map($this->height, $this->centerY, $this->tileSize, $this->zoom);
$diameterPx = intval($arc->radiusInPixel($this->lat, $this->zoom, $this->tileSize) * 2);
if (!($arc->fillColor->isTransparent())) {
$fillColor = $arc->fillColor->allocate($this->image);
if ($arc->isCircle()) {
imagefilledellipse($arcsImage, $centerX, $centerY, $diameterPx, $diameterPx, $fillColor);
} else {
// If start or end angle is close to 90 or 270 degree, we need to render the area of the arc around 90/270°
// in order to circumvent a bug in GD.
// Therefore, we draw the area of the arc as a polygon.
$arcPolyPoints = $arc->getArcPoints($this->centerX, $this->centerY, $this->width, $this->height, $this->zoom, $this->tileSize);
imagefilledpolygon($arcsImage, $arcPolyPoints, count($arcPolyPoints) / 2, $fillColor);
}
}
if ($arc->lineWidth > 0) {
$lineColor = $arc->lineColor->allocate($arcsImage);
if ($arc->isCircle()) {
imagesetthickness($arcsImage, $arc->lineWidth);
// Because imageellipse() ignores imagesetthickness(), we have to use imagearc.
imagearc($arcsImage, $centerX, $centerY, $diameterPx, $diameterPx, 0, 360, $lineColor);
} else {
imagesetthickness($arcsImage, $arc->lineWidth);
imagearc($arcsImage, $centerX, $centerY, $diameterPx, $diameterPx, $arc->start, $arc->end, $lineColor);
if ($arc->straightEdges) {
$arcPoint = $arc->getArcStartOrEnd($this->centerX, $this->centerY, $this->width, $this->height, $this->zoom, $this->tileSize, TRUE);
imageline($arcsImage, $centerX, $centerY, $arcPoint[0], $arcPoint[1], $lineColor);
$arcPoint = $arc->getArcStartOrEnd($this->centerX, $this->centerY, $this->width, $this->height, $this->zoom, $this->tileSize, FALSE);
imageline($arcsImage, $centerX, $centerY, $arcPoint[0], $arcPoint[1], $lineColor);
}
}
}
}
imagecopy($this->image, $arcsImage, 0, 0, 0, 0, $this->width, $this->height);
}
/**
* Build a path where to store a tile to be cached based on its URL.
*
* @return the destination path
*/
public function tileUrlToFilename($url){
return $this->tileCacheBaseDir . "/" . str_replace(array('http://', 'https://'), '', $url);
}
/**
* Check if a tile is available in the cache.
*
* @param url URL the tile was retrieved from.
*
* @return true if found in the cache, false otherwise
*/
public function checkTileCache($url){
$filename = $this->tileUrlToFilename($url);
if(file_exists($filename)){
return file_get_contents($filename);
}
}
/**
* Check if a file is already stored in the map cache.
*
* The cache is file based and uses the MD5 hash of the query parameters as
* key (filename). The MD5 hash is generated from a serialization of the
* parsed parameters, not from the original query string.
*
* There is no expiry mechanism.
*
* This method returns false if the cache is disabled.
*
* @param true if the map was found in the cache, false otherwise
*/
public function checkMapCache(){
if ($this->doNotReadMapCache) return false;
$this->mapCacheID = md5($this->serializeParams());
$filename = $this->mapCacheIDToFilename();
if(file_exists($filename)) return true;
return false;
}
/**
* Helper function for checkMapCache() to provide a string which will be
* hashed and used as key for the cache.
*
* @return MD5 hash of the serialized parameters
*/
public function serializeParams(){
return join("&",array($this->zoom, $this->lat, $this->lon, $this->width, $this->height,
serialize($this->markers), serialize($this->lines), $this->maptype, $this->getApiKey(),
serialize($this->arcs)));
}
/**
* Convert a cache key (MD5 hash) into the path where the image is store.
*/
public function mapCacheIDToFilename(){
//TODO make this a function which receives the hash as a parameter
//instead of using a property of the instance of the class.
if(!$this->mapCacheFile){
$this->mapCacheFile = $this->mapCacheBaseDir . "/" . substr($this->mapCacheID,0,2) . "/"
. substr($this->mapCacheID,2,2) . "/" . substr($this->mapCacheID,4);
}
return $this->mapCacheFile.".".$this->mapCacheExtension;
}
/**
* Create a directory and its parents if they do not exist.
*
* @param pathname path
*
* @param mode file mode bits (Unix file permissions), e.g. 770, as integer
*/
public function mkdir_recursive($pathname, $mode){
is_dir(dirname($pathname)) || $this->mkdir_recursive(dirname($pathname), $mode);
return is_dir($pathname) || @mkdir($pathname, $mode);
}
/**
* Write a tile to be cached to the disk.
*
* @param url URL the tile was downloaded from
*
* @param data binary data of the tile
*/
public function writeTileToCache($url, $data){
$filename = $this->tileUrlToFilename($url);
$this->mkdir_recursive(dirname($filename),0777);
file_put_contents($filename, $data);
}
/**
* Fetch a tile from a URL.
*
* @param url URL the tile should be downloaded from
*/
public function fetchTile($url){
if($this->useTileCache && ($cached = $this->checkTileCache($url))) return $cached;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 300);
curl_setopt($ch, CURLOPT_USERAGENT, "staticmaps.php");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
if ($tile = curl_exec($ch))
{
$statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if($statusCode == 200 && $this->useTileCache){
$this->writeTileToCache($url,$tile);
}
}
else
{
$this->doNotWriteMapCache = 1;
}
$statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($statusCode != 200 && $statusCode != 304) {
$this->statusCode = $statusCode;
curl_close($ch);
throw new Exception('Error: HTTP status code ' . $statusCode . ' returned for tile request ' . $url);
}
curl_close($ch);
return $tile;
}
/**
* Add the copyright notice to the lower right corner of the image.
*
* @param font truetype font file to be used, has to be located in the `fonts/` subdirectory
*/
public function copyrightNotice(){
$attributionText = '© OpenStreetMap contributors';
$font = $this->fontBaseDir.'/' . $this->attributionFont . '.ttf';
$bbox = imagettfbbox(8, 0, $font, $attributionText);
$length = abs($bbox[4] - $bbox[0]);
$height = abs($bbox[5] - $bbox[1]);
$black = imagecolorallocate($this->image, 0, 0, 0);
$transparentWhite = imagecolorallocatealpha($this->image, 255, 255, 255, 60);
imagefilledrectangle($this->image, imagesx($this->image) - $length - 2,
imagesy($this->image) - $height - 4, imagesx($this->image), imagesy($this->image),
$transparentWhite);
imagettftext($this->image, 8, 0, imagesx($this->image) - $length - 1,
imagesy($this->image) - 4, $black, $font, $attributionText);
}
/**
* Send HTTP headers to the client.
*/
public function sendHeader(){
header('Content-Type: image/png');
$expires = 60*60*24*14;
header("Pragma: public");
header("Cache-Control: maxage=".$expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
}
public function makeMap(){
$this->initCoords();
$this->createBaseMap();
if (count($this->lines)) {
$this->placeLines();
}
if (count($this->arcs)) {
$this->placeArcs();
}
if(count($this->markers))$this->placeMarkers();
if($this->attribution) $this->copyrightNotice();
}
public function showMap(){
$this->parseParams();
if($this->useMapCache){
// use map cache, so check cache for map
if(!$this->checkMapCache()){
// map is not in cache, needs to be built
$this->makeMap();
$this->sendHeader();
if (!$this->doNotWriteMapCache)
{
$this->mkdir_recursive(dirname($this->mapCacheIDToFilename()),0777);
imagepng($this->image,$this->mapCacheIDToFilename(),9);
}
if(file_exists($this->mapCacheIDToFilename())){
return file_get_contents($this->mapCacheIDToFilename());
} else {
imagepng($this->image);
}
} else {
// map is in cache
$this->sendHeader();
return file_get_contents($this->mapCacheIDToFilename());
}
} else {
// no cache, make map, send headers and deliver png
$this->makeMap();
$this->sendHeader();
return imagepng($this->image);
}
}
}
$map = new staticMapLite();
print $map->showMap();
?>