AdrenalineJunky
AdrenalineJunky

Reputation: 921

How do you get a random decimal number (positive and negative) in PHP

I wish to randomly position markers on a Google map so hoped to randomly generate the longitude and latitude of the markers using PHP and load them in via AJAX. The problem I have is not only are coordinates decimals but some are negative. For example I need the longitude to be between -2.07137437719725 and -1.92779606909178 and the latitude to be between 50.71603387939352 and 50.793906977546456. The only random functions I can find only work for positive integers so aren't feasible. I did try multiplying the numbers by a billion to remove the decimals and then would later divide the resulting random number by the same amount to return to using decimals but unfortunately PHP can't handle such large numbers.

I hope you can help.

Thanks

Paul

Upvotes: 0

Views: 1929

Answers (2)

dougBTV
dougBTV

Reputation: 1878

Here's a function that I brewed up to do just this. It takes a number of decimal points as an argument and uses a check of a random number even/odd to make the positivity/negativity randomized.

    $latlon = randomLatLon(4);
    print_r($latlon);

    function randomLatLon($granularity) {

            // $granularity = Number of decimal spaces.
            $power = pow(10,$granularity); // Extended 10 to the power of $granularity.

            // Generate the lat & lon (as absolutes) according to desired granularity.
            $lat = rand(0,90 * $power) / $power;
            $lon = rand(0,180 * $power) / $power;

            // Check if a random number is even to randomly make the lat/lon negative.
            if (rand(0,100) % 2 == 0) {
                    $lat = $lat * -1;
            }

            // Same for lon...
            if (rand(0,100) % 2 == 0) {
                    $lon = $lon * -1;
            }

            return array(
                    "lat" => $lat,
                    "lon" => $lon,
            );


    }

Upvotes: 1

TelKitty
TelKitty

Reputation: 3156

You could use something like this:

float Latitudes = (float)((rand(0, 180000000) - 90000000)) / 1000000);
float Latitudes = (float)((rand(0, 360000000) - 180000000)) / 1000000);

Personally I think the accuracy up to 0.001 would be good enough for the locations. If you do not believe me, try it on google map (-32.833, 151.893) & (-32.832, 151.895), see how much further apart they are.

Upvotes: 0

Related Questions