这是我的代码。
Create Table [dbo].[MajorCities]
(
[CityID] int Identity(1,1),
[CityName] varchar(60),
[Latitude] float,
[Longitude] float,
GeoRef Geography
)
INSERT INTO dbo.[MajorCities] values
('New Delhi, India', 28.6, 77.2, null),
('Paris, France', 48.86667, 2.3333, null),
('Rio de Janeiro, Brazil', -22.9, -43.23333, null),
('Sydney, Australia', -33.88306, 151.21667, null),
('New York City, USA', 40.78333, -73.96667, null)
select * from [MajorCities]
UPDATE [dbo].[MajorCities]
SET [GeoRef] = geography::STPointFromText ('POINT (' + CAST ([Longitude] AS VARCHAR (20)) + ' ' +
CAST ([Latitude] AS VARCHAR (20)) + ')', 4326)
我想在KM中找到两个位置之间的距离。
请帮帮我。 感谢。
答案 0 :(得分:21)
如果您的纬度和经度具有度数(就像在表格中一样),那么您可以使用以下功能:
CREATE FUNCTION dbo.DictanceKM(@lat1 FLOAT, @lat2 FLOAT, @lon1 FLOAT, @lon2 FLOAT)
RETURNS FLOAT
AS
BEGIN
RETURN ACOS(SIN(PI()*@lat1/180.0)*SIN(PI()*@lat2/180.0)+COS(PI()*@lat1/180.0)*COS(PI()*@lat2/180.0)*COS(PI()*@lon2/180.0-PI()*@lon1/180.0))*6371
END
OR 如果您坚持使用地理类型,则使用方法为:
DECLARE @g geography;
DECLARE @h geography;
SET @g = geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656)', 4326);
SET @h = geography::STGeomFromText('POINT(-122.34900 47.65100)', 4326);
SELECT @g.STDistance(@h);