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

jerauf's avatar

Getting zip codes based on user's current zip code

I've got a table with all zip codes and their longitude/latitude. I want to be able to query the table based on the user's zip code and a radius, then return all zip codes within that radius.

Does anyone know of a tutorial or has anyone done this? I've been googling and haven't found what I'm looking for.

0 likes
7 replies
Cronix's avatar

How do you have the zipcodes stored? Zipcodes are shapes, which consist of many lat/lng pairs to make a boundary that can be drawn on a map.

As far as the actual query to do what you're asking, google "haversine formula" for whatever db you're using, "mysql haversine" etc.

BGWeb's avatar

I am working on a location management system right now and we are using zip/postal codes to establish relationships between our users and companies in these areas. It is a pretty complicated and frustrating business requirement. With that said, and this may not be appropriate or feasible for you, but you may want to consider using a third-party API to help facilitate this process. Just something to consider.

jerauf's avatar

@cronix - They're stored in a table with associated latitudes and longitudes. So, 41.953256 lat -87.66290 long is zip code 60613. I want to find, for example, all zip codes within 5 miles of that.

Cronix's avatar

@jerauf That won't be accurate at all. You need the full shape of each zipcode. Most zipcode takes hundreds/thousands of gps points. They aren't all just simple box shapes of all the same size, and none are a single point on a map. Most are fairly complex.

jerauf's avatar

@cronix - Then maybe a better way of putting it is to search within 5 miles of a latitude and longitude.

Cronix's avatar
Cronix
Best Answer
Level 67

That's what the haversine formula does that I suggested you google. https://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/

But it will only be as good as the data you're searching against. If you have single points to represent entire geographic areas, it won't be very accurate at all. I could be 20 miles from the gps point that you're using for the zip code, but still be within that zip code. If the search radius is 10 miles, it wouldn't even show where I am correctly, or the zipcodes "close by"

jerauf's avatar

@cronix - I think that did what I need it to do! Thank you for the help!

Please or to participate in this conversation.