我希望两个邮政编码之间的距离。
HTML
表单有一个字段,即ZIP CODE,Miles(距离)。\
包含7000条记录的数据库结构。
id | name | zip_code | lat | lng | status|
MySQL查询
$query = "SELECT *, 3963 * acos(cos(radians(90-lat ))*cos(radians(90-'".$result['lat']."'))".
"+sin(radians(90-lat ))* sin(radians(90-'".$result['lat']."'))".
"*cos(radians(lng- '".$result['lng']."'))) AS distance FROM table_name".
" WHERE memberLevel='basic' HAVING (distance < '".$miles."')
ORDER BY distance ASC";
我不知道什么是正确的MySQL查询来比较距离与输入和存储的纬度,经度。
答案 0 :(得分:1)
您可以使用空间函数和空间类型列http://dev.mysql.com/doc/refman/5.5/en/spatial-extensions.html
这是使用空间功能的一个很好的例子! http://www.mysqlperformanceblog.com/2013/10/21/using-the-new-spatial-functions-in-mysql-5-6-for-geo-enabled-applications/
或者您可以定义自定义功能
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))
result comes in meters