CakePHP搜索2点之间的距离 [英] Search distance between 2 points CakePHP

查看:131
本文介绍了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点之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆