开发者

SQL Select: toilets within 50KM of a certain position?

I need to find toilets around me, say within 50KM, and I have my position in term of latitude and longitude, toilets in database looks like:

Toilet ID (primary)
Address
Latitude
Longitude

my location: my_lat, my_lon

is it possible to construct a statement that returns all toilets within 50KM of (my_lat, my_lon)? Something like

select * from ToiletTable where 
  SQRT((Latitude - my_lat)^2 + (Longitu开发者_开发知识库de - my_lon)^2) < 50

Thanks!


You are looking for the Haversine formula

Here are two full implementations, one in SQL: Haversine Implementation

EDIT:

Here's a Haversine implementation of a UDF in SQLite. Unfortunately it's against the iPhone, but at least you have the exact implementation you need. Now you just need to determine how to plug it in.

SQL inlined below

CREATE FUNCTION [dbo].[GetDistance]

(
  @lat1 Float(8),
  @long1 Float(8),
  @lat2 Float(8),
  @long2 Float(8)
)
RETURNS Float(8)
AS
BEGIN
  DECLARE @R Float(8);
  DECLARE @dLat Float(8);
  DECLARE @dLon Float(8);
  DECLARE @a Float(8);
  DECLARE @c Float(8);
  DECLARE @d Float(8);
  SET @R = 6371; --This value is 6371 for kilometers, 3960 for miles.
  SET @dLat = RADIANS(@lat2 - @lat1);
  SET @dLon = RADIANS(@long2 - @long1);
  SET @a = SIN(@dLat / 2) * SIN(@dLat / 2) + COS(RADIANS(@lat1))
                    * COS(RADIANS(@lat2)) * SIN(@dLon / 2) * SIN(@dLon / 2);
  SET @c = 2 * ASIN(MIN(SQRT(@a)));
  SET @d = @R * @c;
  RETURN @d;
END
GO


Assuming you're not in the polar or pacific regions, i'd use:

where pow(2*(latitude - ?), 2) + pow(longitude - ?, 2) < distance
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜