Joywork/import/YandexMapImage.php
2026-05-22 21:21:54 +03:00

101 lines
2.2 KiB
PHP

<?php
class YandexMapImage
{
const ATTEMPTS_COUNT = 4;
const ATTEMPTS_TIMEOUT = 10;
const DOMAIN = 'http://static-maps.yandex.ru/1.x/';
private $x;
private $y;
private $points = [];
private $width;
private $height;
private $zoom = 10;
private $imageFile = null;
public function __construct($x, $y, $width, $height, $zoom = 10)
{
$this->x = $x;
$this->y = $y;
$this->width = (int)$width;
$this->height = (int)$height;
$this->zoom = (int)$zoom;
}
public function addPoint($x, $y)
{
$this->points[] = [$x, $y];
return $this;
}
private function getPointsString()
{
$points = empty($this->points) ? [[$this->x, $this->y]] : $this->points;
$p = [];
foreach ($points as $point) {
$p[] = implode(',', $point);
}
return implode('~', $p);
}
private function buildUrl()
{
$params = [
'll' => $this->x . ',' . $this->y,
'size' => $this->width . ',' . $this->height,
'z' => (int)$this->zoom,
'l' => 'map',
'pt' => $this->getPointsString(),
];
return self::DOMAIN . '?' . http_build_query($params);
}
private function loadData($url)
{
$data = false;
$attempt = self::ATTEMPTS_COUNT;
do {
if ($attempt != self::ATTEMPTS_COUNT) {
sleep(self::ATTEMPTS_TIMEOUT);
}
try {
$data = file_get_contents($url);
} catch (\Exception $e) {
$data = false;
}
} while (--$attempt > 0 && $data === false);
return $data;
}
private function getTmpFile()
{
if (!empty($this->imageFile) && is_file($this->imageFile)) {
return $this->imageFile;
}
$tmpDir = sys_get_temp_dir();
do {
$filename = $tmpDir.'/'.uniqid();
} while (file_exists($filename));
$data = $this->loadData($this->buildUrl());
file_put_contents($filename, $data);
return $this->imageFile = $filename;
}
public function __toString()
{
return $this->getTmpFile();
}
}