简体   繁体   中英

Find nearest location from point always returning empty

I am trying to some results from my table geo_address I've followed this tutorial by google but the result is always empty. The $lat and $lng are taken from actual data in the table... so at least it should show 1 result.

What I am missing?

$lat = "51.460873";
$lng= "-0.219140";
$radius = "15";
$sql = "SELECT  lat, lng, ( 3959 * acos( cos( radians(':lat') ) * 
cos( radians( lat ) ) * cos( radians( lng ) - radians(':lng') ) 
+ sin( radians(':lat')    ) * sin( radians( lat ) ) ) ) 
AS distance FROM geo_address 
HAVING distance < ':radius' ORDER BY distance LIMIT 0 , 20";
$query = $this->db();
$query = $query->prepare($sql);
$query->bindValue(":lat",$lat);
$query->bindValue(":lng",$lng);
$query->bindValue(":radius",$radius);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
if (empty($result)) {
    echo "empty";
    return;
}

EDIT : I after hardcoding the values into the query, it now returns results, but I cant get it to work with bindValue Why?

ORDER BY distance尝试添加ASC -如果没有订单指示,查询可能会失败。

You are quoting parameters in sql ie ':lat' .

Try removing them.

$sql = "SELECT  lat, lng, ( 3959 * acos( cos( radians(:lat) ) * 
cos( radians( lat ) ) * cos( radians( lng ) - radians(:lng) ) 
+ sin( radians(:lat)    ) * sin( radians( lat ) ) ) ) 
AS distance FROM geo_address 
HAVING distance < :radius ORDER BY distance LIMIT 0 , 20";

Try changing your variables over over to numbers

$lat = "51.460873";
$lng= "-0.219140";
$radius = "15";

Become:

$lat    = 51.460873;
$lng    = -0.219140;
$radius = 15;

And then removing the (unnecessary) quotes from the bind variables in your SQL statement:

radians(':lat')
radians(':long')
distance < ':radius'

Become

radians(:lat)
radians(:long)
distance < :radius
  • The first I'd advise since it makes sense to keep your data-types consistent with their contents, regardless of if this will cause an issue with your particular implementation. It would be very easy to come back to this later and add some more code to this that assumes that lat, lng and radius are numbers when you have defined them as strings.
  • The second change is almost certainly the issue. You don't need the quotes as the process of binding makes such things redundant - it's one of the reasons for using bind variables - the differing behaviours of datatypes is largely taken care of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM