geometry 数据类型方法引用
https://docs.microsoft.com/zh-cn/previous-versions/sql/sql-server-2008/bb933973(v=sql.100)
SQL Server空间数据类型计算某个点是否在多边形内
1、地理坐标系空间需要用geography ,平面坐标系空间用geometry,计算距离使用STDistance
字符串里经纬度的顺序是 “经度[空格]纬度”,即“longitude latitude”。
如果要计算两个lat/lon点之间的实际距离就需要将geometry类型转成geography类型,不然结果不正确。
2、geometry转geography的方法:
geography::STGeomFromText(boundary.ToString(), 4326)
boundary是geometry类型的,4326是坐标系的参数,4326代表GCS-WGS-1984坐标系,是系统默认的坐标系。
可以通过这个sql获得系统的坐标系(Sql server中):Select * from sys.spatial_reference_systems where authorized_spatial_reference_id=4326
3、谷歌地图里得到的多边形(polygon)的顶点定义的顺序和Sql Server里Geography类型中的顶点定义顺序是相反的,即一个是顺时针定义,一个是逆时针定义(至于哪个是顺时针,哪个是逆时针,没有细究),所以把这些顶点存到数据库的时候,需要先反转一下,否则 SQL Server会报异常。
DECLARE @g geography; DECLARE @h geography; SET @g = geography::STGeomFromText(‘POLYGON((-122.358 47.653, -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))‘, 4326); SET @h = geography::Point(47.653, -122.358, 4326) SELECT @g.STIntersects(@h)
转载于:https://blog.csdn.net/weixin_30410119/article/details/96151296
SQL Server地理位置信息计算两点经纬度距离
STDistance的用法:
https://msdn.microsoft.com/zh-cn/library/bb933952(v=sql.110).aspx
按照里面的例子能够计算出距离,但是如果输入的是经纬度的值,得出的结果总是觉得不对,值比较小,实际上需要按照第二步转化为geography类型再计算就可以了,4326坐标系默认返回距离的单位【unit】是米【meter】。
DECLARE @g geography; DECLARE @h geography; SET @g = geography::STGeomFromText(‘POINT(104.12765 31.61)‘, 4326); SET @h = geography::STGeomFromText(‘POINT(114.132179 22.547010)‘, 4326); SELECT @g.STDistance(@h);
创建表和geometry字段以及插入点,线,多边形的sql如下
参考:https://blog.csdn.net/zzq900503/article/details/41349271
IF OBJECT_ID ( ‘dbo.SpatialTable‘, ‘U‘ ) IS NOT NULL DROP TABLE dbo.SpatialTable; GO CREATE TABLE SpatialTable ( id int IDENTITY (1,1), geom geometry, adress varchar ); GO INSERT INTO SpatialTable (geom) VALUES (geometry::STGeomFromText(‘POINT (20 180)‘, 4326)); INSERT INTO SpatialTable (geom) VALUES (geometry::STGeomFromText(‘LINESTRING (100 100, 20 180, 180 180)‘, 4326)); INSERT INTO SpatialTable (geom) VALUES (geometry::STGeomFromText(‘POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))‘, 4326)); GO
选取圆形区域范围的 地址---也就是 圆心到半径范围内的所有点
DECLARE @g geometry; set @g = geometry::STGeomFromText(‘POINT(104.12765 30.60445)‘, 4326) SELECT address,geom.STY,geom.STX from SpatialTable where geom.STDistance(@g)<=0.005
选取多边形
DECLARE @g geometry; set @g = geometry::STGeomFromText(‘POLYGON ((104.12189573049204 30.608145728994504,104.12223905324595 30.60282680842528,104.13262456655161 30.603122311674902,104.13176625966685 30.610066378528995,104.12189573049204 30.608145728994504,104.12189573049204 30.608145728994504))‘,4326) SELECT address from SpatialTable where geom.STIntersects(@g)=1