Introduction
There are many websites with similar functionality: find a doctor near your home, find the closest store, and search for apartments. I didn't realize until I needed to make such a site that finding a doctor near your home is fairly difficult.
Suppose I have a database with 10,000 doctors located all over the country. Each one has an address, including a postal code. For each postal code, I have an associated latitude and longitude.
When a user enters his own address, including postal code, I can get the latitude and longitude from the same table.
Now I have a problem. Here is a SQL Server function to calculate the distance in miles between two points for which I have latitude and longitude.
CREATE FUNCTION [dbo].[CalculateDistance]
(
@lat1Degrees decimal(10,6),
@lon1Degrees decimal(10,6),
@lat2Degrees decimal(10,6),
@lon2Degrees decimal(10,6)
)
RETURNS decimal(9,4)
AS
BEGIN
DECLARE @earthSphereRadiusKilometers as decimal(10,6)
DECLARE @kilometerConversionToMilesFactor as decimal(7,6)
SELECT @earthSphereRadiusKilometers = 6366.707019
SELECT @kilometerConversionToMilesFactor = .621371
-- convert degrees to radians
DECLARE @lat1Radians decimal(10,6)
DECLARE @lon1Radians decimal(10,6)
DECLARE @lat2Radians decimal(10,6)
DECLARE @lon2Radians decimal(10,6)
SELECT @lat1Radians = (@lat1Degrees / 180) * PI()
SELECT @lon1Radians = (@lon1Degrees / 180) * PI()
SELECT @lat2Radians = (@lat2Degrees / 180) * PI()
SELECT @lon2Radians = (@lon2Degrees / 180) * PI()
-- formula for distance from [lat1,lon1] to [lat2,lon2]
RETURN ROUND(2 * ASIN(SQRT(POWER(SIN((@lat1Radians - @lat2Radians) / 2) ,2)
+ COS(@lat1Radians) * COS(@lat2Radians) * POWER(SIN((@lon1Radians - @lon2Radians) / 2), 2)))
* (@earthSphereRadiusKilometers * @kilometerConversionToMilesFactor), 4)
END
That's a lot of math for the database to do. If I have 10,000 doctors and I want to find the ones that are near my user's address, I could run all 10,000 addresses through this function and select the ones that are nearby. That's simply unworkable. It would be far too slow. If I had several users searching for doctors at the same time it would overwhelm the server. I need a way to only calculate the distance for doctors I already know are close.
A Little About Latitude And Longitude
Degrees of latitude is about 69 miles apart. That is, a latitude of 40.000 is about 69 miles away from a latitude of 39.000. So if I want to find doctors within 30 miles of a given point, I can rule out any address whose latitude is more than .5 degrees north or south of my location.
Longitude is somewhat more complicated. Near the poles, lines of longitude are very close. At the equator, they are much further apart. In the continental United States, lines of longitude are roughly 53 miles apart. So if I want to find doctors within 30 miles then I should look for ones whose longitude is no more than .6 degrees east or west of my location.
Now I don't have to calculate the distance for every doctor in my database. I can look for addresses whose latitude and longitude are close to the user's location.
Here's a SQL Server Stored Procedure that uses this technique to select postal codes near a given location. It uses the CalculateDistance function shown above.
-- =============================================
-- Description: Get all zip codes within ~30 miles north, south, east or west of the input location.
-- =============================================
/*
exec [dbo].[ZipCodesNearLatLong] 37.000495, -94.840850
*/
CREATE PROCEDURE [dbo].[ZipCodesNearLatLong]
@Latitude DECIMAL(10,6),
@Longitude DECIMAL(10,6)
AS
BEGIN
SET NOCOUNT ON;
select distinct
PC.ZipCode,
PC.Latitude,
PC.Longitude,
dbo.CalculateDistance(@Latitude, @Longitude, PC.Latitude, PC.Longitude) as Distance
from PostalCodes PC
where (ABS(@Latitude - PC.Latitude) < .5) -- Lines of latitude are ~69 miles apart.
and (ABS(@Longitude - PC.Longitude) < .6) -- Lines of longitude in the U.S. are ~53 miles apart.
order by Distance
END
Now that I can get a list of nearby postal codes, I can get a list of doctors in these postal codes.
-- =============================================
-- Description: Search for a doctor near a specified zip code.
-- @LastName is optional
-- =============================================
/*
exec [FindDoctorByNameAndZipCode] 43001, 'Fenster'
*/
CREATE PROCEDURE [dbo].[FindDoctorByNameAndZipCode]
@ZipCode CHAR(5),
@LastName VARCHAR(50) = NULL,
AS
BEGIN
SET NOCOUNT ON;
IF (@LastName = '')
SELECT @LastName = NULL
ELSE
SELECT @LastName = @LastName + '%'
-- Get latitude and longitude for the zip code
DECLARE @Latitude DECIMAL(10,6)
DECLARE @Longitude DECIMAL(10,6)
EXECUTE [dbo].[LatitudeAndLongitudeForZipCode] @ZipCode,@Latitude OUTPUT ,@Longitude OUTPUT
-- Get a table of zip codes
DECLARE @ZipCodes TABLE
(
ZipCode CHAR(5),
Latitude DECIMAL(10,6),
Longitude DECIMAL(10,6),
Distance DECIMAL(10,1)
)
INSERT INTO @ZipCodes EXECUTE [dbo].[ZipCodesNearLatLong] @Latitude, @Longitude
-- Search
SELECT DISTINCT TOP 50
DR.ProviderID,
DR.Title,
DR.FirstName,
DR.LastName,
DR.Address1,
DR.City,
DR.StateAbbreviation,
DR.ZipCode,
DR.Phone,
DR.Gender,
Z.Distance
FROM Doctors DR
JOIN @ZipCodes Z
ON DR.ZipCode = Z.ZipCode
WHERE ((P.LastName LIKE @LastName) OR (@LastName IS NULL))
ORDER BY Z.Distance
END
Conclusion
This article taught us how to find a doctor nar your home in SQL Server. If you're using SQL Server, the geography data type and associated SQL Server functions can be used to calculate distances and search for nearby locations. Performance can be slow. Although I have provided SQL Server examples, my goal was to describe a method that is not limited to SQL Server.