Ini milik kita. Anda mungkin perlu memodifikasinya untuk struktur tabel Anda. Kami mencari lokasi ritel (dan fasilitasnya), bukan kota, tetapi bagian tersulitnya adalah "jarak terdekat" yang berfungsi dalam pernyataan ini.
CREATE PROCEDURE [dbo].[GetNearbyLocations] @CenterLatitude FLOAT, @CenterLongitude FLOAT
AS
DECLARE @CntXAxis FLOAT
DECLARE @CntYAxis FLOAT
DECLARE @CntZAxis FLOAT
SET @CntXAxis = COS(RADIANS(@CenterLatitude)) * COS(RADIANS(@CenterLongitude))
SET @CntYAxis = COS(RADIANS(@CenterLatitude)) * SIN(RADIANS(@CenterLongitude))
SET @CntZAxis = SIN(RADIANS(@CenterLatitude))
SELECT LocationId, LocationName, Address, City, State, Zip, Phone, Latitude, Longitude,
hasATM, hasCarWash, hasDiesel, hasE85, is24hr, hasTrendar, hasWiFi, isTravelCenter, isMiniTravelCenter, isTruckerFriendly, hasScale, hasHotFood,
ProxDistance = 3961 * ACOS( dbo.XAxis(latitude, longitude)*@CntXAxis + dbo.YAxis(latitude, longitude)*@CntYAxis + dbo.ZAxis(latitude)*@CntZAxis)
FROM Locations
WHERE latitude IS NOT NULL
ORDER BY ProxDistance ASC
GO
Edit - ditambahkan (maaf awalnya saya melewatkan ini)
-- USER-DEFINED FUNCTIONS
-- XAxis #########################################
CREATE FUNCTION [dbo].[XAxis] (@lat float, @lon float)
RETURNS float
AS
BEGIN
RETURN COS(4 * (4 * atn2(1, 5) - atn2(1, 239)) / 180 * @lat) * COS(4 * (4 * atn2(1, 5) - atn2(1, 239)) / 180 * @lon)
END
CREATE FUNCTION [dbo].[YAxis] (@lat float, @lon float)
RETURNS float AS
BEGIN
RETURN COS(4 * (4 * atn2(1,5) - atn2(1,239)) / 180 * @lat) * SIN(4 * (4 * atn2(1,5) - atn2(1,239)) / 180 * @lon)
END
CREATE FUNCTION [dbo].[ZAxis] (@lat float)
RETURNS float AS
BEGIN
RETURN SIN(4 * (4 * atn2(1,5) - atn2(1,239)) / 180 * @lat)
END