Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find zip codes within a range of miles? [closed]

I have a db with clients zip codes, I want to create a page where the user input a zip code and select for example 50 miles and press search, then the page should show all other clients which have zip codes withing the range of this 50 miles.
Means near the given zip code within 50 miles radius.
Is there an API, Lib or something can give me this feature?

like image 205
Amr Elgarhy Avatar asked Dec 31 '25 01:12

Amr Elgarhy


1 Answers

If you're using sql 2008 or later you can use the sys.geography data type to store your locational data in the database and let the server do the calculating for you. That way you can save your API calls for other things.

This works if you're using some sort of geocoding service like Google Maps or Bing to get and store the locational data of your zip codes.

I've done this with a simple stored procedure to great effect in my latest project

CREATE PROCEDURE [dbo].[RadiusSearch]
    @point varchar(500),
    @distance int
AS
begin
    declare @geoPoint geography
    set @geoPoint = geography::STGeomFromText('POINT (' + @point + ')', 4326).STBuffer(@distance / 0.0006213712)
    select [Whatever fields and inner joins you need to get the info you wanted]
    where ClientZipCodes.Geolocation.STIntersects(@geoPoint) = 1
end

So basically what I'm doing is passing in the point data as a string and converting it into binary geographical point data (because in this instance I'm setting off the stored proc from an asynchronous javascript call from a web page, this is unnecessary if you're querying geographical data directly from the database), setting the distance variable to miles (this requires conversion because the default measurement is in meters) and then telling it to give me whatever records have Geolocation points that intersect the buffer we just set up. Easy peezy and quick to boot.

like image 167
Dan S. Avatar answered Jan 01 '26 14:01

Dan S.