6

我的目标是使用 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;     

尝试使用该功能搜索前:

 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): Illegal non geometry 'aswkb(a@0)' value found during paring, or ERROR 1416 (22003): Cannot get geometry object from data you sent to the GEOMETRY field

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

我也尝试过这个解决方案:Find the distance between two points in MYSQL。(使用点数据类型)

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

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

4

2 回答 2

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 以获得以公里为单位的近似值。结果不准确,但“ok”。如果有人知道更好的方法,请随时发表评论。

于 2012-07-12T11:49:26.780 回答
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))

结果以米为单位

于 2013-01-02T12:27:18.317 回答