views:

176

answers:

4

Group,

I'm looking for a query that can do a location search in radians with in a binding box. With a table structure like

ProductID,latitude,longitude,timestampGMT.

Any helpful suggestions.

Chad

+2  A: 

You are looking for the "Great Circle" distance formula

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=81360

Should point you to the correct SQL algorithm

Neil N
+3  A: 

SQL Server 2008 supports GEOGRAPHY datatype.

You should store lat, lon in a single column of this datatype, create a SPATIAL index over it and use it in a query:

SELECT  m.*
FROM    mytable
ON      coords.STDistance(@mypoint) <= @mydistance
Quassnoi
Chad is working on 2003, which doesn't have spatial indexes.
Byron Sommardahl
@Byron: seems I missed the release of `SQL Server 2003` :)
Quassnoi
@Quassnoi: yeah. So did I. :) I meant 2005, but now that I read the question, he was using Windows Server 2003 and never mentioned his SQL version number.
Byron Sommardahl
A: 

You may also want to take a look at this:

SQL Server ZipCode Latitude Longitude Proximity Distance Search

G Mastros
+1  A: 

This question shouldn't be a community wiki. Switch it if you can. Either way, here is your answer.

@Quassnoi gave a great solution for SQL 2008, but you're asking for 2005, right? 2005 doesn't have the same geography support as 2008. You'll have to roll your own as I did. It's not hard, depending on the level of accuracy that you require. Here's a scalar-function that I came up with based on a popular formula for calculating distance between two sets of coordinates:

-- =====================================================================
-- Author:      Byron Sommardahl
-- Create date: June 15, 2007
-- Description: Calculates the distance between two sets of coordinates.
-- ======================================================================
CREATE FUNCTION [dbo].[Distance]
(
@lat1 float,
@long1 float,
@lat2 float,
@long2 float
)
RETURNS float
AS
BEGIN

RETURN (3958*3.1415926*sqrt((@lat2-@lat1)*(@lat2-@lat1) + cos(@lat2/57.29578)*cos(@lat1/57.29578)*(@long2-@long1)*(@long2-@long1))/180);
END
GO

To use this, just feed in your coords using a SELECT:

SELECT dbo.Distance(MyPlace.Lat, MyPlace.Long, TheirPlace.Lat, TheirPlace.Long);

Then, you could just check whether a product is within a certain radius of your focal point. Not exactly bounding box, but it gets you moving in the right direction.

Byron Sommardahl
There is no SQL Server 2003
Chris
@Chris: My mistake. I meant 2005. Getting my version numbers mixed up for sure!
Byron Sommardahl