0

I am using the following query for Radius Search.

$sqlstring2 = "SELECT DISTINCT 
  geodb.postcode,
  (
    6367.41 * SQRT(
      2 * (
        1- COS(RADIANS(geodb.latitude)) * COS(".$lat.") * (
          SIN(RADIANS(geodb.longitude)) * SIN(".$lng.") + COS(RADIANS(geodb.longitude)) * COS(".$lng.")
        ) - SIN(RADIANS(geodb.latitude)) * SIN(".$lat.")
      )
    )
  ) AS Distance 
FROM
  geodb AS geodb 
WHERE (
    6367.41 * SQRT(
      2 * (
        1- COS(RADIANS(geodb.latitude)) * COS(".$lat.") * (
          SIN(RADIANS(geodb.longitude)) * SIN(".$lng.") + COS(RADIANS(geodb.longitude)) * COS(".$lng.")
        ) - SIN(RADIANS(geodb.latitude)) * SIN(".$lat.")
      )
    ) <= '".$radius."'
  ) 
ORDER BY Distance ";

Is there any wrong with this query?? Could anyone help me in this regard??

Thanks

Update

I am using below code

<?php
$postcode = 'E1 0AA';
$radius = 1;

$conn = mysql_connect('127.0.0.1','root','') or die('db connect error:'.mysql_error());
mysql_select_db('database', $conn) or die('could not select database');

$sqlstring = "SELECT * FROM geodb WHERE postcode ='".$postcode."'";
$result = mysql_query($sqlstring);   

$row = mysql_fetch_assoc($result);

$lng = $row["longitude"] / 180 * M_PI;
$lat = $row["latitude"] / 180 * M_PI;

mysql_free_result($result);    

$sqlstring2 = "SELECT DISTINCT geodb.postcode, (6367.41*SQRT(2*(1-cos(RADIANS(geodb.latitude))*cos(".$lat.")*(sin(RADIANS(geodb.longitude))*sin(".$lng.")+cos(RADIANS(geodb.longitude))*cos(".$lng."))-sin(RADIANS(geodb.latitude))* sin(".$lat.")))) AS Distance FROM geodb AS geodb WHERE (6367.41*SQRT(2*(1-cos(RADIANS(geodb.latitude))*cos(".$lat.")*(sin(RADIANS(geodb.longitude))*sin(".$lng.")+cos(RADIANS(geodb.longitude))*cos(".$lng."))-sin(RADIANS(geodb.latitude))*sin(".$lat."))) <= '".$radius."') ORDER BY Distance";

$result1 = mysql_query($sqlstring2) or die('query failed: ' . mysql_error());

echo  mysql_num_rows($result1);

die();

This code gives me result

1215

But if I search in

http://www.freemaptools.com/find-uk-postcodes-inside-radius.htm

with postcode E1 0AA and 1 mile radius I am getting result 4 (E1,E1W,E77,E98).

Could anyone say Where is the problem ??

Thanks

Foysal Vai
  • 1,365
  • 3
  • 13
  • 19

1 Answers1

2

Reduce the workload by doing the calculation only once for each record

$sqlstring2 = "SELECT DISTINCT 
  geodb.postcode,
  (
    6367.41 * SQRT(
      2 * (
        1- COS(RADIANS(geodb.latitude)) * COS(".$lat.") * (
          SIN(RADIANS(geodb.longitude)) * SIN(".$lng.") + COS(RADIANS(geodb.longitude)) * COS(".$lng.")
        ) - SIN(RADIANS(geodb.latitude)) * SIN(".$lat.")
      )
    )
  ) AS Distance 
FROM
  geodb AS geodb 
HAVING Distance <= '".$radius."'
ORDER BY Distance ";

Reduce it still further by calculating a bounding box in PHP and applying that as a WHERE clause in the SQL query

Community
  • 1
  • 1
Mark Baker
  • 209,507
  • 32
  • 346
  • 385