MySQL8.0提供了很多基础的空间分析函数,在GIS开发中,掌握空间数据库的应用是必不可少,也是成长为全栈开发所需必要知识点。本文简单介绍 基于Mysql8.0 的空间函数的简单应用。
### 官方文档 https://dev.mysql.com/doc/refman/8.0/en/spatial-analysis-functions.html
### 5.7 中文 https://www.mysqlzh.com/doc/177/149.html
-- 记录生成geojson格式
SELECT JSON_OBJECT('id',id,'name',`name`,'type', 'feature','properties', JSON_OBJECT('id',id,'name',`name`) ,'geometry',ST_AsGeoJSON(geo)) as geom FROM poi;
-- 获取多要素集合
SELECT ST_Collect(geo) FROM poi WHERE id = 2 OR id = 3 OR id = 5;
-- 查询wkt格式要素
SELECT ST_AsText(geo) FROM poi;
SELECT ST_GeomFromText(ST_AsText(geo)) FROM poi;
-- 每个要素生成单独feature
SELECT ST_AsGeoJSON(geo) as result FROM poi;
-- 获取整个表的空间数据,生成geojson
SELECT ST_AsGeoJSON(ST_Collect(geo)) FROM poi;
-- 获取要素外接矩形
SELECT ST_AsGeoJSON(ST_MakeEnvelope((SELECT geo FROM poi WHERE id = 45),(SELECT geo FROM poi WHERE id = 2))) AS result;
-- 获取两点椭球距离 unit: meter
SELECT ST_Distance_Sphere((SELECT geo FROM poi WHERE id = 3),(SELECT geo FROM poi WHERE id = 5)) AS result;
###
-- 空间关系函数
###
-- 1. 判断完全包含关系
SELECT ST_Contains((SELECT geo FROM poi WHERE id = 66),(SELECT geo FROM poi WHERE id = 3)) AS result;
-- 2. 判断相交关系(line)
SELECT ST_Crosses((SELECT geo FROM poi WHERE id = 7),(SELECT geo FROM poi WHERE id = 6)) AS result;
-- 3. 判断不相交 (0 相交,1 不相交)
SELECT ST_Disjoint((SELECT geo FROM poi WHERE id = 7),(SELECT geo FROM poi WHERE id = 66)) AS result;
-- 4. 距离
SELECT ST_Distance((SELECT ST_GeomFromText(ST_AsText(ST_SwapXY(geo)), 4326) FROM poi WHERE id = 3),(SELECT ST_GeomFromText(ST_AsText(ST_SwapXY(geo)), 4326) FROM poi WHERE id = 5), 'metre');
-- 获取外凸壳
SELECT ST_ConvexHull((SELECT ST_Collect(geo) FROM poi WHERE id = 2 OR id = 3 OR id = 5 OR id = 45));
-- 要素差 g1-g2
SELECT ST_Difference((SELECT geo FROM poi WHERE id = 7), (SELECT geo FROM poi WHERE id = 8));
-- 简化要素
SELECT ST_Simplify(geo, 0.2) ,ST_Simplify(geo, 0.5) ,ST_Simplify(geo, 0.7) ,ST_Simplify(geo, 1) ,geo FROM poi WHERE `id`= 10;
CREATE TABLE `poi` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
`geo` geometry DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=68 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
1 road MULTILINESTRING((10 10, 11 11), (9 9, 10 10))
2 3 POINT(3 3)
3 654 POINT(102.37 35.0048)
5 4123 POINT(102.371 35.0049)
6 3452 MULTILINESTRING((10 10, 11 11), (9 9, 10 10))
7 3452356 MULTILINESTRING((11 10, 10 11), (9 9, 10 10))
8 24562 MULTILINESTRING((11 10, 10 11))
10 54thfg LINESTRING(0 0, 0 1, 1 1, 1 2, 2 2, 2 3, 3 3)
19 46629 LINESTRING(0 0, 0 1, 1 1, 1 2, 2 2, 2 3, 3 3)
45 2 POINT(1 2)
66 552 POLYGON((102.371 35.0049, 102.249 33.8775, 102.227 33.9519, 102.34 35.0212, 102.371 35.0049))
67 sdh5 POINT(1 2)