使用POINT的Mysql空间距离 - 不工作

时间:2012-07-11 15:44:21

标签: mysql geolocation geospatial spatial

我的目标是使用mysql POINT(lat,long)来查找数据库中的附近实体。我正在尝试执行本教程底部http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL之类的操作。这是我得到的:

表:

CREATE TABLE mark (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) DEFAULT NULL,
loc POINT NOT NULL,
SPATIAL KEY loc (loc)
) ENGINE=MyISAM;

插入一些测试数据:

 INSERT INTO mark (loc,name) VALUES (POINT(59.388433,10.415039), 'Somewhere 1');
 INSERT INTO mark (loc,name) VALUES (POINT(63.41972,10.39856), 'Somewhere 2');

声明距离函数:

 DELIMITER $$
 CREATE FUNCTION `distance`
 (a POINT, b POINT)
 RETURNS double DETERMINISTIC
 BEGIN
 RETURN
 round(glength(linestringfromwkb(linestring(asbinary(a),
 asbinary(b)))));
 END $$
 DELIMITER;     

尝试使用该功能搜索ex。:

 SELECT name, distance(mark.loc, GeomFromText( ' POINT(31.5 42.2) ' )) AS cdist
 FROM mark
 ORDER BY
 cdist limit 10;

或:

 SELECT DISTINCT
 dest.name,
 distance(orig.loc, dest.loc) as sdistance
 FROM
 mark orig,
 mark dest
 having sdistance < 10
 ORDER BY
 sdistance limit 10;

我得到的问题是:ERROR 1367(22007):在解析过程中发现非法的非几何'aswkb(@ 0)'值,或者 ERROR 1416(22003):无法从发送到GEOMETRY字段的数据中获取几何对象

我似乎无法弄清楚如何解决这个问题。重要的是“距离”功能可以动态使用。

我也试过这个解决方案:Find the distance between two points in MYSQL. (using the Point Datatype)

这是我的mysql版本mysql Ver 14.14 Distrib 5.5.23,for Linux(x86_64)使用readline 5.1

希望有人的专业知识可以帮助我。干杯!

2 个答案:

答案 0 :(得分:7)

所以我最终将此作为计算距离的查询,例如:

 SELECT  glength(LineStringFromWKB(LineString(GeomFromText(astext(PointFromWKB(POINT(63.424818,10.402457)))),GeomFromText(astext(PointFromWKB(POINT(663.422238,10.398996)))))))*100 
 AS distance;

我将它乘以100得到公里的近似值。结果不准确,但“确定”。如果有人知道更好的方式,请随时发表评论。

答案 1 :(得分:3)

定义自定义函数

CREATE DEFINER=`test`@`%` FUNCTION `geoDistance`(`lon1` DOUBLE, `lat1` DOUBLE, `lon2` DOUBLE, `lat2` DOUBLE)
    RETURNS double
    LANGUAGE SQL
    DETERMINISTIC
    NO SQL
    SQL SECURITY DEFINER
    COMMENT ''
    BEGIN
    DECLARE v DOUBLE;
    SELECT cos(radians(lat1))
        * cos(radians(lat2))
        * cos(radians(lon2) - radians(lon1)) 
        + sin(radians(lat1)) 
        * sin(radians(lat2)) INTO v;
    RETURN IF(v > 1, 0, 6371000 * acos(v));
END

然后致电

SELECT geoDistance(X(point1), Y(point1), X(spoint2), Y(point2))

结果以米为单位