Reputation: 621
Im searching a database with the latitude and longitude of a location. I want to retrieve all of the locations within a certain radius.
I then encode the returned results into a JSON and retrieve the data using ajax, however I get an undefined error meaning that there is no data returned from the database.
Can anybody see where im going wrong?
Heres my query
$sql="SELECT *, ACOS( SIN( RADIANS( `lat` ) ) * SIN( RADIANS( $fLat ) ) + COS( RADIANS( `lat` ) )
* COS( RADIANS( $fLat )) * COS( RADIANS( `lng` ) - RADIANS( $fLon )) ) * 6380 AS `distance`
FROM `markers`
WHERE ACOS( SIN( RADIANS( `lat` ) ) * SIN( RADIANS( $fLat ) ) + COS( RADIANS( `lat` ) )
* COS( RADIANS( $fLat )) * COS( RADIANS( `lng` ) - RADIANS( $fLon )) ) * 6380 < 10
ORDER BY `distance`";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows);
Upvotes: 6
Views: 16065
Reputation: 41
Try this one:
$sql="SELECT * , ACOS( SIN( RADIANS( 'lat' ) ) * SIN( RADIANS( $fLat ) ) + COS( RADIANS( 'lat' ) ) * COS( RADIANS( $fLat )) * COS( RADIANS( 'lng' ) - RADIANS( $fLon )) ) * 6380 AS distance FROM 'markers'
WHERE distance < 10
ORDER BY distance";
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result));
echo json_encode($rows); `
Upvotes: 1
Reputation: 6057
I'm not much help with trig or SQL, I've just seen enough Google maps questions to point you to this tutorial:
https://developers.google.com/maps/articles/phpsqlsearch#findnearsql
There is a query for finding spots by distance in a radius that you can try, hope it works for you.
Use 3959 (in miles) or 6371 (in km)
Upvotes: 6