8

这是我的问题,我有一个包含位置和纬度/经度的 SQLite 表。基本上我需要:

SELECT location, HAVERSINE(lat, lon) AS distance FROM location ORDER BY distance ASC;

HAVERSINE()是一个 PHP 函数,它应该返回给定一对纬度和经度值的大圆距离(以英里或公里为单位)。其中一对应由 PHP 提供,另一对应由表中可用的每个纬度/经度行提供locations

由于 SQLite 没有任何地理空间扩展(AFAIK SpatiaLite存在,但仍然......)我猜最好的方法是使用带有 PDO 方法之一的自定义函数:

我认为这种情况PDO::sqliteCreateFunction()就足够了,但是我对这个函数的有限经验可以减少到类似于 PHP 手册中提供的用例:

$db = new PDO('sqlite:geo.db');

function md5_and_reverse($string) { return strrev(md5($string)); }

$db->sqliteCreateFunction('md5rev', 'md5_and_reverse', 1);
$rows = $db->query('SELECT md5rev(filename) FROM files')->fetchAll();

我在弄清楚如何获得 SQLite 用户定义的函数来同时处理来自 PHP 和表数据的数据时遇到了一些麻烦,如果有人可以帮助我解决这个问题,同时也理解 SQLite UDF,我将不胜感激(一个巨大的胜利SQLite IMO) 好一点。

提前致谢!

4

3 回答 3

9

到目前为止,我只能想到这个解决方案:

$db = new PDO('sqlite:geo.db');

$db->sqliteCreateFunction('ACOS', 'acos', 1);
$db->sqliteCreateFunction('COS', 'cos', 1);
$db->sqliteCreateFunction('RADIANS', 'deg2rad', 1);
$db->sqliteCreateFunction('SIN', 'sin', 1);

然后执行以下冗长的查询:

SELECT "location",
       (6371 * ACOS(COS(RADIANS($latitude)) * COS(RADIANS("latitude")) * COS(RADIANS("longitude") - RADIANS($longitude)) + SIN(RADIANS($latitude)) * SIN(RADIANS("latitude")))) AS "distance"
FROM "locations"
HAVING "distance" < $distance
ORDER BY "distance" ASC
LIMIT 10;

如果有人能想到更好的解决方案,请告诉我。


我刚刚发现了这个有趣的链接,我明天试试。

于 2010-01-18T07:51:41.180 回答
3

From your "interesting link".

function sqlite3_distance_func($lat1,$lon1,$lat2,$lon2) {
    // convert lat1 and lat2 into radians now, to avoid doing it twice below
    $lat1rad = deg2rad($lat1);
    $lat2rad = deg2rad($lat2);
    // apply the spherical law of cosines to our latitudes and longitudes, and set the result appropriately
    // 6378.1 is the approximate radius of the earth in kilometres
    return acos( sin($lat1rad) * sin($lat2rad) + cos($lat1rad) * cos($lat2rad) * cos( deg2rad($lon2) - deg2rad($lon1) ) ) * 6378.1;
}

$db->sqliteCreateFunction('DISTANCE', 'sqlite3_distance_func', 4);

Then do a query with:

"SELECT * FROM location ORDER BY distance(latitude,longitude,{$lat},{$lon}) LIMIT 1"

EDIT (by QOP): I finally needed this again and this solution worked out great, I just ended up modifying the code a bit to it is a bit less verbose and handles non-numeric values gracefully, here it is:

$db->sqliteCreateFunction('distance', function () {
    if (count($geo = array_map('deg2rad', array_filter(func_get_args(), 'is_numeric'))) == 4) {
        return round(acos(sin($geo[0]) * sin($geo[2]) + cos($geo[0]) * cos($geo[2]) * cos($geo[1] - $geo[3])) * 6378.14, 3);
    }

    return null;
}, 4);
于 2013-04-16T09:06:56.147 回答
0

Building off Alix's answer...

$db->sqliteCreateFunction('HAVERSINE', 'haversine', 2);

I would imagine that this would allow the query that you specified in your question to work.

于 2010-01-18T14:55:09.050 回答