XTRUST.ORG
XTRUST.ORG

Reputation: 3392

Random points (Lat, Lng) in bounding box

I want to find random point with latitude/longitude in the bounding box.

I have bounding box defined below:

[bbox] => Object (
   [lat] => Array (
     [min] => 51.319503485716
     [max] => 56.169129950579
   )
   [lon] => Array (
     [min] => 23.199493849386
     [max] => 32.693643019346
   )
)

My function:

$x_max  = $polygon->bbox['lat']['max'];
$x_min  = $polygon->bbox['lat']['min'];
$y_max  = $polygon->bbox['lon']['max'];
$y_min  = $polygon->bbox['lon']['min'];

$lat    = $y_min + mt_rand($y_min, $y_max);
$lng    = $x_min + mt_rand($x_min, $x_max);

But the function above returns wrong results.

How can I fix it?

Upvotes: 2

Views: 915

Answers (1)

Bob__
Bob__

Reputation: 12759

You need a float random number, while mt_rand returns an int. Try with this:

$lat = $y_min + ($y_max - $y_min) * (mt_rand() / mt_getrandmax());
$lng = $x_min + ($x_max - $x_min) * (mt_rand() / mt_getrandmax());

Upvotes: 1

Related Questions