Home >Database >Mysql Tutorial >MySQL中判断一个点是否落在多边形内

MySQL中判断一个点是否落在多边形内

WBOY
WBOYOriginal
2016-06-07 17:22:512190browse

关于地理空间数据,经常需要处理两个空间数据的关联关系。有很多种方法可以处理,通过编写程序算法,或者是调用数据库中对应的fu

关于地理空间数据,经常需要处理两个空间数据的关联关系。有很多种方法可以处理,通过编写程序算法,或者是调用数据库中对应的function。在mysql数据库中,做了详细的介绍,但是它并没有真正的实现多边形(5.6版本之前),,本文以判断一个点是否落在多边形内的主题,加以简单的扩展。

首先,建立一张简单的地理数据表,

CREATE TABLE `ci_special_zone` ( 
  `id` int(11) NOT NULL auto_increment, 
  `ploygongeo` text NOT NULL, 
  PRIMARY KEY  (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

并插入几条数据

INSERT INTO ci_special_zone (ploygongeo) VALUES('POLYGON((113.547 22.186,113.549 22.186,113.549 22.188, 113.547 22.188,113.547 22.186))'); 
INSERT INTO ci_special_zone (ploygongeo) VALUES('POLYGON((112.547 21.186,112.549 212.186,112.549 21.188, 112.547 212.188,112.547 21.186))'); 

创建function,

DELIMITER // 
 
CREATE FUNCTION myWithin(p POINT, poly POLYGON) RETURNS INT(1) DETERMINISTIC 
BEGIN 
DECLARE n INT DEFAULT 0; 
DECLARE pX DECIMAL(9,6); 
DECLARE pY DECIMAL(9,6); 
DECLARE ls LINESTRING; 
DECLARE poly1 POINT; 
DECLARE poly1X DECIMAL(9,6); 
DECLARE poly1Y DECIMAL(9,6); 
DECLARE poly2 POINT; 
DECLARE poly2X DECIMAL(9,6); 
DECLARE poly2Y DECIMAL(9,6); 
DECLARE i INT DEFAULT 0; 
DECLARE result INT(1) DEFAULT 0; 
SET pX = X(p); 
SET pY = Y(p); 
SET ls = ExteriorRing(poly); 
SET poly2 = EndPoint(ls); 
SET poly2X = X(poly2); 
SET poly2Y = Y(poly2); 
SET n = NumPoints(ls); 
WHILE iSET poly1 = PointN(ls, (i+1)); 
SET poly1X = X(poly1); 
SET poly1Y = Y(poly1); 
IF ( ( ( ( poly1X ( poly2Y - poly1Y ) * ( pX - poly1X ) / ( poly2X - poly1X ) + poly1Y ) ) THEN 
SET result = !result; 
END IF; 
SET poly2X = poly1X; 
SET poly2Y = poly1Y; 
SET i = i + 1; 
END WHILE; 
RETURN result; 
End; 
// 
DELIMITER ; 

最后,执行如下的sql语句

SELECT substring(ploygongeo,10,length(ploygongeo)-11) from ci_special_zone 
where myWithin(PolygonFromText('Point(113.547 22.186)'),PolygonFromText(ploygongeo))>0 limit 0,1 

坐标点113.547 22.186是经纬度,若有返回值,则表示坐标点落在所在的区间。

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn