I
I
Ilya2018-05-13 19:16:20
PHP
Ilya, 2018-05-13 19:16:20

How to find the nearest metro station to a specific address?

I parse the addresses of Moscow libraries. How can I get one nearest metro station by address in 2018?

$address = 'Москва, ул. Габричевского, 8';
echo findMetro($address); // Щукинская

JS maps API latest version at the moment

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya, 2018-05-20
@sidorchik

$address = 'ул. Габричевского, 8';
echo findMetro($address); // Щукинская

function findMetro($address) {
    // Определение координат заданного адреса
    $address = str_replace(' ', '%20', $address);
    $contentGeocoder = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?key=QWERTY1234&address=Москва,%20$address"); // ключ получил на console.developers.google.com/apis
    $jsonGeocoder = json_decode($contentGeocoder, true);
    $latitudeFrom = $jsonGeocoder["results"][0]["geometry"]["location"]["lat"];
    $longitudeFrom = $jsonGeocoder["results"][0]["geometry"]["location"]["lng"];

    // Подключение к базе данных с таблицей метро
    include '../php/db_connection.php';
    $link = mysqli_connect($host, $user, $password, $database) or die("Не удалось подключиться к базе данных");

    // Определение ближайшего метро путём перебора
    $min = 10000000;
    for($metroI = 1; $metroI <= 250; $metroI++) {
        // Запрос на выборку для определения координат и названия станции метро
        $result = mysqli_query($link, "SELECT name, latitude, longitude FROM metro WHERE id = $metroI");
        $row = mysqli_fetch_assoc($result);

        // Вычисление расстояния между заданным адресом и станцией метро по формуле Хаверсина
        $latFrom = deg2rad($latitudeFrom);
        $lonFrom = deg2rad($longitudeFrom);
        $latTo = deg2rad($row[latitude]);
        $lonTo = deg2rad($row[longitude]);
        $latDelta = $latTo - $latFrom;
        $lonDelta = $lonTo - $lonFrom;
        $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) + cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
        $distance = $angle * 6371000;

        // Если расстояние до станции метро меньше, чем минимальное найденное,— назначаем его минимальным, запоминаем название
        if($distance < $min) {
            $min = $distance;
            $closestMetro = $row[name];
        }
    }
    return $closestMetro;
}

DB table with metro : station name, coordinates by latitude, longitude

A
Andrew, 2018-05-17
@iCoderXXI

There are a finite number of metro stations, I added their coordinates to the base, and then, using the hypotenuse method, calculated the distances in parrots from the desired point to different stations and took the nearest ones within a certain radius.
You can even decide without a base, it will be even faster and more autonomous. Even without a backend you can, for that matter.

G
German Zvonchuk, 2018-05-17
@inside22

Using https://developers.google.com/places/supported_typ... get a list of all stations in the desired radius, save it all to the database. You will have stations and coordinates.
Next, you pass the address of the library and get the coordinates, also collect it all in the database.
https://maps.googleapis.com/maps/api/geocode/json?...
Next, pass the metro and library coordinates to this function and it will return the distance to you.

public function getDistance(float $latitudeFrom, float $longitudeFrom, float $latitudeTo, float $longitudeTo): int
    {
        $rad = M_PI / 180;
        $theta = $longitudeFrom - $longitudeTo;
        $dist = sin($latitudeFrom * $rad) * sin($latitudeTo * $rad) + cos($latitudeFrom * $rad) * cos($latitudeTo * $rad) * cos($theta * $rad);

        return acos($dist) / $rad * 60 * 1.853;
    }

You can get tired and use the Google Matrix API to calculate how much to stomp on foot and how much to drive by car.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question