File: //var/www/elite/coordParser/Yandex.php
<?php
namespace coordParser;
class Yandex
{
const URL = 'https://geocode-maps.yandex.ru/1.x/';
// Ключ Яндекс Геокодера
const API_KEY = 'e1c5022a-67f4-4f75-b9db-6caf3086d693';
// Необходимо указать так же как в ключе в Яндексе иначе не работает
const REFERER = 'http://limestate-elite.ru';
private function errorExit(string $message): array
{
echo $message . PHP_EOL;
return ['longitude' => '', 'latitude' => ''];
}
public function getCoordinatesFromGeocoder(string $address): array
{
if (empty($address)) {
return ['longitude' => '', 'latitude' => ''];
}
print_r('Получаем координаты для адреса: «' . $address . '»' . PHP_EOL);
$query = [
'apikey' => self::API_KEY,
'geocode' => str_replace(' ', '+', mb_strtolower($address)),
'format' => 'json',
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, self::URL . '?' . http_build_query($query));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_REFERER, self::REFERER);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true);
if (JSON_ERROR_NONE != json_last_error()) {
return $this->errorExit('Произошла ошибка получения данных');
}
if (isset($response['statusCode']) && 200 != $response['statusCode']) {
return $this->errorExit('Ошибка: ' . ($response['error'] ?? 'Неизвестная ошибка') . ' ' . ($response['message'] ?? ''));
}
$pos = $response['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos'] ?? null;
if (empty($pos)) {
return $this->errorExit('В ответе нет координат');
}
[$longitude, $latitude] = explode(' ', $pos);
return compact('longitude', 'latitude');
}
}