Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mbo's avatar
Level 3

Selecting location within range

Goodday,

I'm trying to do the following:

Search locations within a range of a certain point based on latitude and longitude. I got this working going through the list of points and calculate the distance to the point. Then i filter them by distance to find the locations within the range.

part of the script:

  $lat1 = deg2rad($postcode->latitude);
                        $lon1 = deg2rad($postcode->longitude);
                        $lat2 = deg2rad(floatval($latitude));
                        $lon2 = deg2rad(floatval($longitude));
    
                        $delta_lat = $lat2 - $lat1;
                        $delta_lng = $lon2 - $lon1;
    
                        $hav_lat = (sin($delta_lat / 2))**2;
                        $hav_lng = (sin($delta_lng / 2))**2;
    
                        $distance = 2 * asin(sqrt($hav_lat + cos($lat1) * cos($lat2) * $hav_lng));
    
                        $earth_radius_km = 6371.009;
    
                        $actual_distance = $earth_radius_km * $distance;


But now i want to find the zip codes near a point. Also based on latitude and longitude. But now we got almost 50.000 zip codes. I don't want to use the method above because i then have to go through all zip codes and calculate the distance. A process whats costs a lot of serverpower.

I'am wondering if there is way to pre select zipcodes who could be in the range. So i can first select the zipcodes where i can be useful to calculate the distance. Then i can run those zip codes through the way i described above.

Anyone any tips for this?

thanks in advance.

0 likes
1 reply
sr57's avatar
sr57
Best Answer
Level 39

Put zip code in groups based on 'logic of zipcode' or your own logic and choose zipcodes in the nearby groups.

Let's say you define 'square group', you can reduce to nine groups, the one where original zipcode is and the 8 around. You jsut have to define the length of a square and constuct these data one time.

Please or to participate in this conversation.