Reputation:
$test_1 = mysql_query("SELECT id,name,l_name,foto_profili FROM users");
while($test = mysql_fetch_array($test_1)){
$testid = $test['id'];
$test_2 = mysql_query("SELECT kordinata_x,kordinata_y FROM lokacioni WHERE id_user=$testid");
while($riinvest = mysql_fetch_array($test_2)){
$qr_x = $riinvest['kordinata_x'];
$qr_y = $riinvest['kordinata_y'];
if($qr_x<=$qr_x+0.001452||$qr_x<=$qr_x-0.001452&&$qr_y<=$qr_y+0.001877||$qr_y<=$qr_y-0.001877){
echo 'othercode goes here';
}
}
}
So there is a button where user can send the location of his/her to the database and I am trying to make a check if that user location is inside a circle with a radius of 50m
My problem is that when this code runs all users that have a location saved pop up and the 50m radius code doesnt work
Upvotes: 0
Views: 61
Reputation: 2815
Your problem is the if-condition.
Simplified, you do this comparation:
a <= a + x
or
a <= a - x
and
b <= b + y
or
b <= b - y
As some value is always less or equal to the same value plus some other (positive) value, the first and third condition are always true. You must not compare the user coordinates with themselves.
Furthermore, your condition tries to apply a square area instead of a circular area. To calculate the distance, convert the longitude and latitude values to metric positions. Then apply this formula:
distance := sqrt((x2-x1)^2 + (y2-y1)^2)
If the result is less or equal to 50, the condition is true.
Based on your code it would look like this in PHP. My PHP isn't very well anymore, so it might contain syntax errors:
$test_1 = mysql_query("SELECT id,name,l_name,foto_profili FROM users");
while($test = mysql_fetch_array($test_1)){
$testid = $test['id'];
$test_2 = mysql_query("SELECT kordinata_x,kordinata_y FROM lokacioni WHERE id_user=$testid");
while($riinvest = mysql_fetch_array($test_2)){
$qr_x = $riinvest['kordinata_x'];
$qr_y = $riinvest['kordinata_y'];
<!-- coordToMeters is a fictional function, you have to implement some function that converts coordinates into meters -->
$qr_x_meters = coordToMeters($qr_x);
$qr_y_meters = coordToMeters($qr_y);
<!-- you'll need to provide the coordinates of the center of the circle the users coordinates are checked to be within -->
$comp_x = ???;
$comp_y = ???;
<!-- again, you have to convert them into meters -->
$comp_x_meters = coordToMeters($comp_x);
$comp_y_meters = coordToMeters($comp_y);
<!-- calculate the distance from the circles center to the users position -->
$distance = sqrt(($comp_x_meters - $qr_x_meters)^2 + ($comp_y_meters - $qr_y_meters)^2);
if($distance <= 50){
<!-- do whatever you want to do for those user within the circle -->
}
}
}
Upvotes: 1