A Kuijk
A Kuijk

Reputation: 51

Find closest 10 cities with MySQL using latitude and longitude?

I have searched the Web a lot to find the solution for my problem but I still can't figure it out.

I have a very simple database with id, city name, latitude, longitude and city_info. When someone enters a city page a would like to show the 10 nearby cities.

How can I calculate this with MySQL and return it with PHP?

I have seen a lot of suggestions on this website, however none of these work somehow.

What I tried without success. I do not get any results.

<?php
$slatitude = 43.2141341;
$slongitude = 64.4368684;
$miles = 200;

//connect

$query = "SELECT *, 
( 3959 * acos( cos( radians('$slatitude') ) * 
cos( radians( latitude ) ) * 
cos( radians( longitude ) - 
radians('$slongitude') ) + 
sin( radians('$slatitude') ) * 
sin( radians( latitude ) ) ) ) 
AS distance FROM cities HAVING distance < '$miles' ORDER BY distance ASC LIMIT 0, 10";

$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0){

while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$cityname = $row['cityname'];
$latitude = $row['latitude'];
$longitude = $row['longitude'];

echo "$cityname<br />";

}}

?>`

Upvotes: 3

Views: 6426

Answers (5)

MelArlo
MelArlo

Reputation: 157

Here is a query I use to get the closest zip codes from a given latitude/longitude set. The table is very simple:

id, zip, lat, lng

This query assumes your center point is using "$slatitude: and :$slongitude". This will return all matches that are within the distance variable "$miles" (i.e. 3, 2.4, 1000). In my script the results are put in to an array and asorted for closest X number of results.

$getzip = mysql_query("SELECT zip,((ACOS(SIN(".$slatitude." * PI() / 180) * SIN(lat * PI() / 180) + COS(".$slatitude." * PI() / 180) * COS(lat * PI() / 180) * COS((".$slongitude." - lng) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM zips HAVING distance<='$miles' ORDER BY 'distance' ASC", $link2) or die (mysql_error($link2));

Hope it helps!

Upvotes: 1

Bryan Gmyrek
Bryan Gmyrek

Reputation: 21

To improve the speed of your query you could first limit the set of results that you'll do calculations for using something like the sub-select below (note that I also used a different method for calculating the distance - it works for me, ymmv). In my tests, using the where clause with a tolerance of 1 was over 100 times faster than the query without it.

...
$tol = 1; // limits the search to lat/long within 1 from the given values
$query_args = array($lat,$long,$lat-$tol,$lat+$tol,$long-$tol,$long+$tol);
$query = "
  SELECT *,latitude, longitude, 
    SQRT( POW( 69.1 * ( latitude - %s) , 2 ) 
        + POW( 69.1 * ( %s - longitude ) 
          * COS( latitude / 57.3 ) , 2 ) ) 
    AS distance FROM zipcodes
      WHERE latitude > %d AND latitude < %d 
      AND longitude > %d AND longitude < %d 
  ORDER BY distance ASC limit 10
";
...

Upvotes: 2

david strachan
david strachan

Reputation: 7228

I have used PDO for this as mysql_ functions are being deprecated

<?php
 //Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);//Change to suit 
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    // Prepare statement
    $stmt = $dbh->prepare("SELECT  *, ( 3959 * acos( cos( radians(?) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(?) ) + sin( radians(?) ) * sin( radians( lat ) ) ) ) AS distance FROM cities HAVING distance < ? ORDER BY distance LIMIT 0 , 10");
    // Assign parameters
    $stmt->bindParam(1,$slatitude);
    $stmt->bindParam(2,$slongitude);
    $stmt->bindParam(3,$slatitude);
    $stmt->bindParam(4,$miles);
    //Execute query
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $stmt->execute();
    if ($stmt->rowCount()>0) { 
    // Iterate through the rows
    while($row = $stmt->fetch()) {
        $id = $row['id'];
        $cityname = $row['cityname'];
        $latitude = $row['latitude'];
        $longitude = $row['longitude'];
        echo "$cityname<br />";]);
        }
    }
   else{
        echo "No Records";
       }   
}

catch(PDOException $e) {
    echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing 
    file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", mapSelect.php, ". $e->getMessage()."\r\n", FILE_APPEND);  
 }
//Close the connection
$dbh = null; 
?>

This DEMO uses this query

Upvotes: 0

Ian Overton
Ian Overton

Reputation: 1060

You can't use having because your not grouping by anything. What you need to do is repeat what you did in the select in the where.

$query = "SELECT *, 
( 3959 * acos( cos( radians('$slatitude') ) * 
cos( radians( latitude ) ) * 
cos( radians( longitude ) - 
radians('$slongitude') ) + 
sin( radians('$slatitude') ) * 
sin( radians( latitude ) ) ) ) 
AS distance FROM cities WHERE ( 3959 * acos( cos( radians('$slatitude') ) * 
cos( radians( latitude ) ) * 
cos( radians( longitude ) - 
radians('$slongitude') ) + 
sin( radians('$slatitude') ) * 
sin( radians( latitude ) ) ) ) < '$miles' ORDER BY distance ASC LIMIT 0, 10";

or you could do something like this:

$query = "
SELECT * FROM (
  select *, 
  ( 3959 * acos( cos( radians('$slatitude') ) * 
  cos( radians( latitude ) ) * 
  cos( radians( longitude ) - 
  radians('$slongitude') ) + 
  sin( radians('$slatitude') ) * 
  sin( radians( latitude ) ) )) as distance from cities
) WHERE distance < '$miles' ORDER BY distance ASC LIMIT 0, 10";

Upvotes: 2

Teson
Teson

Reputation: 6736

the far most easy solution would be:

get the coordinates for the city and

select ...
order by abs(`Latt`-reqLatt) * abs(`Long`-reqLong)

it isn't perfect but you'd be able to sort out what you want from the top 50.

Upvotes: 0

Related Questions