lnelson92 lnelson92 - 6 months ago 13
SQL Question

Search database with lat and long by radius using php mysql

Im trying to develop a small site which retrieves a results from a database by a set radius and places them on a map.
I use Google maps api to get the lat and long from there search criteria, pass these to my php script which queries the database and returns the result set as a JSON object.

Im having small a problem sending both the lat and long to the php using json.

My main problem is that my sql to search the database appears to be wrong as it just retrieves the first 10 results in my database. I want it to return the first 10 results within the radius from the search point.

Here is my ajax code

function showCarPark(location)
{
var lat = location.lat();
var lng = location.lng();
//alert("Lat: " +lat.toFixed(6));
//alert("Lng: " +lng.toFixed(6));
document.getElementById('carParkResults').innerHTML = "";
var criterion = document.getElementById("address").value;
var count = 0;
$.ajax({
url: 'process.php',
type: 'GET',
data: "lat=" + lat + "&lng=" + lng,
dataType: 'json',
success: function(data)
{
jQuery.each(data, function()
{
$('<p>').text("Car Park: " + data[count].name).appendTo('#carParkResults');
placeCarParks(data[count].postcode,data[count].name, data[count].street, data[count].type);
count++;
});
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error" + e.message);
}
});


And here is my php script

$rad = 20;
$lat = $_GET['lat'];
$lng = 1.4681464; //put a temporary number in as it wont pass the lng in the JSON

$sql="SELECT *, (3959 * acos(cos(radians('".$lat."')) * cos(radians(lat)) * cos( radians(long) - radians('".$lng."')) + sin(radians('".$lat."')) *
sin(radians(lat))))
AS distance
FROM carpark HAVING distance < 15 ORDER BY distance LIMIT 0 , 10";

$result = mysql_query($sql);

while($r = mysql_fetch_assoc($result)) $rows[] = $r;

echo json_encode($rows);


The columns in my table are called lat and long
Any help is appreciated.

Answer

For your case try to use WHERE instead of HAVING

SELECT *, (3959 * acos(cos(radians('".$lat."')) * cos(radians(lat)) * cos( radians(long) - radians('".$lng."')) + sin(radians('".$lat."')) * 
sin(radians(lat)))) 
AS distance 
FROM carpark WHERE distance < 15 ORDER BY distance LIMIT 0 , 10
Comments