CakePHP搜索2点之间的距离

编程入门 行业动态 更新时间:2024-10-28 03:29:50
本文介绍了CakePHP搜索2点之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我试图建立一个小型的CakePHP网站,它在数据库中有一些经纬度。用户对位置执行搜索查询(给出她/他的地址),并且结果需要按用户到位置的距离排序。提供地址时(使用Google地图API),我已经可以获得经纬度了。 我不确定如何使用距离命令构建CakePHP查找。 任何想法?

我使用CakePHP 2.3。

解决方案

我更喜欢为此使用virtualFields。实施取决于您使用的数据库。对于Postgres,它将如下所示:

MyModel.php

public function findSortedByDistanse($ long,$ lat){ $ distanceValue =calc_distance($ lat,$ long,MyModel.lat,MyModel.lon); $ this-> virtualFields ['distance'] = $ distanceValue; return $ this-> find('all',array('conditions'=> array('order'=&>'MyModel.distance ASC'))); }

其中calc_distance是Postgres的存储过程

参数: IN source_lat数字,IN source_lon数字,IN target_lat数字,IN target_lon数字 $ b 代码: $ p $ SELECT(3956 * 2 * ASIN( SQRT($ b $ ($($ 1 - abs($ 3))* pi()/ 180/2),2)+ COS($ 1 * pi()/ 180)* COS )* pi()/ 180)* POWER(SIN(($ 2 - $ 4)* pi()/ 180/2),2))))

如果您更喜欢原始查询,请使用以下内容:

$ distanceValue =3956 * 2 * ASIN(SQRT(POWER(SIN(({$ lat} -abs(MyModel.lat))* pi()/ 180/2), 2)+ COS({$ lat} * pi()/ 180)* COS(abs(MyModel.lat)* pi()/ 180)* POWER(SIN(({$ long} - MyModel.lon)* pi )/ 180/2),2)));

Im trying to build a small CakePHP website which has some lat and longitudes in the DB. A user performs a search query to locations (with giving her/his address) and the results needs to be ordered by distance from user to the location. I can already get the lat en lng when providing an adress (using the Google Maps API). I'm not sure how to build a CakePHP find with an distance order. Any ideas?

I'm using CakePHP 2.3.

解决方案

I prefer to use virtualFields for this purpose. The implementation depends on DB you use. For Postgres it will look like following:

MyModel.php

public function findSortedByDistanse($long, $lat){ $distanceValue = "calc_distance($lat, $long, MyModel.lat, MyModel.lon)"; $this->virtualFields['distance'] = $distanceValue; return $this->find('all', array('conditions' => array( 'order' => 'MyModel.distance ASC' ))); }

where calc_distance is a stored procedure for Postgres

Params: IN source_lat numeric, IN source_lon numeric, IN target_lat numeric, IN target_lon numeric

Code:

SELECT ( 3956 * 2 * ASIN ( SQRT ( POWER ( SIN ( ( $1 - abs($3) ) * pi()/180/2 ),2 ) + COS ( $1 * pi()/180 ) * COS ( abs($3) * pi()/180 ) * POWER ( SIN ( ( $2 - $4 ) * pi()/180 / 2 ), 2 ) ) ) )

If you prefer raw query, use following:

$distanceValue = "3956 * 2 * ASIN(SQRT(POWER(SIN(({$lat}-abs(MyModel.lat))*pi()/180/2),2)+COS({$lat} * pi()/180)*COS(abs(MyModel.lat) * pi()/180)*POWER(SIN(({$long} - MyModel.lon)*pi()/180 / 2), 2)))";

更多推荐

CakePHP搜索2点之间的距离

本文发布于:2023-10-27 22:31:17,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:距离   CakePHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!