mjaschen / phpgeo

Simple Yet Powerful Geo Library for PHP
https://phpgeo.marcusjaschen.de
MIT License
1.56k stars 195 forks source link

Find all objects within specific Distance #81

Closed mwsasser closed 3 years ago

mwsasser commented 3 years ago

Is it possible to find all the objects within a specified distance from a given location?

I've been using Haversine to do this with an old php 5 class. But I'm not sure how you'd do that with this library.

The examples show how to find distance between two specific locations. But I'd like to find all the locations within X miles or km, ordered by distance. Is that possible?

I already have a populated database table with all of the locations. They are postal codes with latitude and longitude columns.

Thanks for your help!

mjaschen commented 3 years ago

It sounds as if a simple loop over all records with a distance calculation against the reference point would solve your problem:

$referenceLocation = new Coordinate(52.5, 13.5);
$calculator = new Haversine();
$inside = [];
foreach ($locations as $location) {
    if ($reference->distance($location, $calculator) <= 1000) {
        $inside[] = $location;
    }
}

$inside will contain all records with a radius of 1,000 meters around $reference.

mwsasser commented 3 years ago

Thank you @mjaschen.