How to organize by proximity using PHP?

4

I have some locations registered in the database and each of them has the longitude and latitude. When the user enters the site, I ask him to report his geolocation. I'm using the library PHPGeo to compute the distance between each, but how can I organize this result?

Ex: Location 1, Location 2, Location 3

I'm closer to Local 2 , then Local 3 and then Local 1 .

How do I organize this?

    
asked by anonymous 28.05.2014 / 17:39

2 answers

9

Starting from PHPGeo itself, as mentioned in the question:

Vincenty's Formula

<?php
   use Location\Coordinate;
   use Location\Distance\Vincenty;
   $coordenada1 = new Coordinate( -23.575, -46.658 );
   $coordenada2 = new Coordinate( -21.279, -44.297 );
   $calculadora = new Vincenty();
   echo $calculadora->getDistance( $coordenada1, $coordenada2 );
?>


Haversine Formula

The Haversine formula is much faster to calculate, but less accurate.

<?php
   use Location\Coordinate;
   use Location\Distance\Haversine;
   $coordenada1 = new Coordinate( -23.575, -46.658 );
   $coordenada2 = new Coordinate( -21.279, -44.297 );
   $calculadora = new Haversine();
   echo $calculadora->getDistance( $coordenada1, $coordenada2 );
?>

GitHub - PHPGeo


Calculating the distance from the origin to several points, and sorting:

To sort the results, you can start from the reference point, and in a loop store the calculated distances in an array, and then sort them:

<?php
    $origem       = new Coordinate( -22.155, -45.158 );

    // Lembre-se de inicializar as arrays de acordo com seu código
    $nome[1] = 'Ponto1';
    $coordenada[1] = new Coordinate( -23.575, -46.658 );

    $nome[2] = 'Ponto2';
    $coordenada[2] = new Coordinate( -21.279, -44.297 );

    $nome[3] = 'Ponto3';
    $coordenada[3] = new Coordinate( -21.172, -44.017 );
    ... etc ...

    // Vamos calcular a distância de todos para a $origem:
    $calculadora = new Haversine();
    $count = count( $coordenada );
    for ($i = 0; $i < $count; $i++) {
       $distancia[i] = calculadora->getDistance( $origem, $coordenada[i] );
    }

    // Agora ordenamos os pontos de acordo com a $distancia:
    array_multisort( $distancia, $coordenada, $nome );
?>
    
28.05.2014 / 20:17
0

First you need to know your location in coordinates. Then you calculate the distances between the starting point (you) and the other points, using the haversine formula, or some feature of PHPGEO if it has, I do not know. So you get the smallest value and that's the shortest distance, with this logic you can put the distances in an array, so array [0] - > shorter distance, array [1] - > second shortest distance ...

    
28.05.2014 / 18:09