]> Raphaël G. Git Repositories - packbundle/blob - Util/OsmUtil.php
Remove debug
[packbundle] / Util / OsmUtil.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys PackBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\PackBundle\Util;
13
14 use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
15 use Symfony\Component\Filesystem\Filesystem;
16
17 /**
18 * Helps manage osm images
19 */
20 class OsmUtil {
21 /**
22 * The tile size
23 */
24 const tz = 256;
25
26 /**
27 * The cache directory
28 */
29 protected $cache;
30
31 /**
32 * The public path
33 */
34 protected $path;
35
36 /**
37 * The tile server
38 */
39 protected $server;
40
41 /**
42 * The tile servers
43 *
44 * @see https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
45 */
46 protected $servers = [
47 'osm' => 'https://tile.openstreetmap.org/{Z}/{X}/{Y}.png',
48 'cycle' => 'http://a.tile.thunderforest.com/cycle/{Z}/{X}/{Y}.png',
49 'transport' => 'http://a.tile.thunderforest.com/transport/{Z}/{X}/{Y}.png'
50 ];
51
52 /**
53 * The public url
54 */
55 protected $url;
56
57 /**
58 * Creates a new osm util
59 *
60 * @param string $cache The cache directory
61 * @param string $path The public path
62 * @param string $url The public url
63 * @param string $server The server key
64 */
65 function __construct(string $cache, string $path, string $url, string $server = 'osm') {
66 //Set cache
67 $this->cache = $cache.'/'.$server;
68
69 //Set path
70 $this->path = $path.'/'.$server;
71
72 //Set url
73 $this->url = $url.'/'.$server;
74
75 //Set server key
76 $this->server = $server;
77 }
78
79 /**
80 * Return the image
81 *
82 * @desc Generate image in jpeg format or load it from cache
83 *
84 * @param string $pathInfo The path info
85 * @param string $alt The image alt
86 * @param int $updated The updated timestamp
87 * @param float $latitude The latitude
88 * @param float $longitude The longitude
89 * @param int $zoom The zoom
90 * @param int $width The width
91 * @param int $height The height
92 * @return array The image array
93 */
94 public function getImage(string $pathInfo, string $alt, int $updated, float $latitude, float $longitude, int $zoom = 18, int $width = 1280, int $height = 1280): array {
95 //Set path file
96 $path = $this->path.$pathInfo.'.jpeg';
97
98 //Without existing path
99 if (!is_dir($dir = dirname($path))) {
100 //Create filesystem object
101 $filesystem = new Filesystem();
102
103 try {
104 //Create path
105 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
106 $filesystem->mkdir($dir, 0775);
107 } catch (IOExceptionInterface $e) {
108 //Throw error
109 throw new \Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
110 }
111 }
112
113 //With path file
114 if (
115 is_file($path) &&
116 ($stat = stat($path)) &&
117 $stat['mtime'] >= $updated
118 ) {
119 //Return image data
120 return [
121 'src' => $this->url.'/'.$stat['mtime'].$pathInfo.'.jpeg',
122 'alt' => $alt,
123 'height' => $height,
124 'width' => $width
125 ];
126 }
127
128 //Create image instance
129 $image = new \Imagick();
130
131 //Add new image
132 $image->newImage($width, $height, new \ImagickPixel('transparent'), 'jpeg');
133
134 //Create tile instance
135 $tile = new \Imagick();
136
137 //Init context
138 $ctx = stream_context_create(
139 [
140 'http' => [
141 #'header' => ['Referer: https://www.openstreetmap.org/'],
142 'max_redirects' => 5,
143 'timeout' => (int)ini_get('default_socket_timeout'),
144 #'user_agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36',
145 'user_agent' => (string)ini_get('user_agent')?:'rapsys_air/2.0.0',
146 ]
147 ]
148 );
149
150 //Get tile xy
151 $tileX = floor($centerX = $this->longitudeToX($longitude, $zoom));
152 $tileY = floor($centerY = $this->latitudeToY($latitude, $zoom));
153
154 //Calculate start xy
155 $startX = floor(($tileX * self::tz - $width) / self::tz);
156 $startY = floor(($tileY * self::tz - $height) / self::tz);
157
158 //Calculate end xy
159 $endX = ceil(($tileX * self::tz + $width) / self::tz);
160 $endY = ceil(($tileY * self::tz + $height) / self::tz);
161
162 for($x = $startX; $x <= $endX; $x++) {
163 for($y = $startY; $y <= $endY; $y++) {
164 //Set cache path
165 $cache = $this->cache.'/'.$zoom.'/'.$x.'/'.$y.'.png';
166
167 //Without cache path
168 if (!is_dir($dir = dirname($cache))) {
169 //Create filesystem object
170 $filesystem = new Filesystem();
171
172 try {
173 //Create path
174 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
175 $filesystem->mkdir($dir, 0775);
176 } catch (IOExceptionInterface $e) {
177 //Throw error
178 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
179 }
180 }
181
182 //Without cache image
183 if (!is_file($cache)) {
184 //Set tile url
185 $tileUri = str_replace(['{Z}', '{X}', '{Y}'], [$zoom, $x, $y], $this->servers[$this->server]);
186
187 //Store tile in cache
188 file_put_contents($cache, file_get_contents($tileUri, false, $ctx));
189 }
190
191 //Set dest x
192 $destX = intval(floor(($width / 2) - self::tz * ($centerX - $x)));
193
194 //Set dest y
195 $destY = intval(floor(($height / 2) - self::tz * ($centerY - $y)));
196
197 //Read tile from cache
198 $tile->readImage($cache);
199
200 //Compose image
201 $image->compositeImage($tile, \Imagick::COMPOSITE_OVER, $destX, $destY);
202
203 //Clear tile
204 $tile->clear();
205 }
206 }
207
208 //Add circle
209 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
210 $draw = new \ImagickDraw();
211
212 //Set text antialias
213 $draw->setTextAntialias(true);
214
215 //Set fill color
216 $draw->setFillColor('#cff');
217
218 //Set stroke color
219 $draw->setStrokeColor('#00c3f9');
220
221 //Set stroke width
222 $draw->setStrokeWidth(2);
223
224 //Draw circle
225 $draw->circle($width/2 - 5, $height/2 - 5, $width/2 + 5, $height/2 + 5);
226 #$draw->circle($tileX/self::tz - 5, $tileY/self::tz - 5, $tileX/self::tz + 5, $tileY/self::tz + 5);
227
228 //Draw on image
229 $image->drawImage($draw);
230
231 //Strip image exif data and properties
232 $image->stripImage();
233
234 //Add latitude
235 //XXX: not supported by imagick :'(
236 $image->setImageProperty('exif:GPSLatitude', $this->latitudeToSexagesimal($latitude));
237
238 //Add longitude
239 //XXX: not supported by imagick :'(
240 $image->setImageProperty('exif:GPSLongitude', $this->longitudeToSexagesimal($longitude));
241
242 //Add description
243 //XXX: not supported by imagick :'(
244 $image->setImageProperty('exif:Description', $alt);
245
246 //Save image
247 if (!$image->writeImage($path)) {
248 //Throw error
249 throw new \Exception(sprintf('Unable to write image "%s"', $dest));
250 }
251
252 //Get dest stat
253 $stat = stat($path);
254
255 //Return image data
256 return [
257 'src' => $this->url.'/'.$stat['mtime'].$pathInfo.'.jpeg',
258 'alt' => $alt,
259 'height' => $height,
260 'width' => $width
261 ];
262 }
263
264 /**
265 * Convert longitude to tile x number
266 *
267 * @see https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_5
268 *
269 * @param float $longitude The longitude
270 * @param int $zoom The zoom
271 *
272 * @return float The tile x
273 */
274 public function longitudeToX(float $longitude, int $zoom): float {
275 return (($longitude + 180) / 360) * pow(2, $zoom);
276 }
277
278 /**
279 * Convert latitude to tile y number
280 *
281 * @see https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_5
282 *
283 * @param $latitude The latitude
284 * @param $zoom The zoom
285 *
286 * @return float The tile y
287 */
288 public function latitudeToY(float $latitude, int $zoom): float {
289 return (1 - log(tan(deg2rad($latitude)) + 1 / cos(deg2rad($latitude))) / pi()) / 2 * pow(2, $zoom);
290 }
291
292 /**
293 * Convert tile x to longitude
294 *
295 * @param float $x The tile x
296 * @param int $zoom The zoom
297 *
298 * @return float The longitude
299 */
300 public function xToLongitude(float $x, int $zoom): float {
301 return $x / pow(2, $zoom) * 360.0 - 180.0;
302 }
303
304 /**
305 * Convert tile y to latitude
306 *
307 * @param float $y The tile y
308 * @param int $zoom The zoom
309 *
310 * @return float The latitude
311 */
312 public function yToLatitude(float $y, int $zoom): float {
313 return rad2deg(atan(sinh(pi() * (1 - 2 * $y / pow(2, $zoom)))));
314 }
315
316 /**
317 * Convert decimal latitude to sexagesimal
318 *
319 * @param float $latitude The decimal latitude
320 *
321 * @return string The sexagesimal longitude
322 */
323 public function latitudeToSexagesimal(float $latitude): string {
324 //Set degree
325 $degree = $latitude % 60;
326
327 //Set minute
328 $minute = ($latitude - $degree) * 60 % 60;
329
330 //Set second
331 $second = ($latitude - $degree - $minute / 60) * 3600 % 3600;
332
333 //Return sexagesimal longitude
334 return $degree.'°'.$minute.'\''.$second.'"'.($latitude >= 0 ? 'N' : 'S');
335 }
336
337 /**
338 * Convert decimal longitude to sexagesimal
339 *
340 * @param float $longitude The decimal longitude
341 *
342 * @return string The sexagesimal longitude
343 */
344 public function longitudeToSexagesimal(float $longitude): string {
345 //Set degree
346 $degree = $longitude % 60;
347
348 //Set minute
349 $minute = ($longitude - $degree) * 60 % 60;
350
351 //Set second
352 $second = ($longitude - $degree - $minute / 60) * 3600 % 3600;
353
354 //Return sexagesimal longitude
355 return $degree.'°'.$minute.'\''.$second.'"'.($longitude >= 0 ? 'E' : 'W');
356 }
357 }