Find Random Coordinates Within a Boundary

When testing a location-enabled app or site, you’re going to need various locations for testing. One way to find these points is to pop open Google Maps and clicking around, copying these points, and pasting them into your site/app.

This is what I did. For about 5 minutes. Before I remember I was a developer.

Scenario

I need to find random points throughout the U.S. with as little effort on my part as possible.

Architecture

  • Feed it known bounds
  • Find a point within those bounds

Execution

First, we need some points. I opened up Google Maps, and grabbed 4 points which roughly outlined the continental U.S.:

Four points that give us a rough outline of the continental U.S.

Take these four points and add them to an array:

Now we need to find the minimum X, maximum X, minimum Y and maximum Y within our points.

Then we can get a random point within our min/max bounds. Because we want number that look like coordinates (a float rounded to 6 places), we’ll do some math.

This will get a random percentage (mt_rand() / mt_getrandmax()), multiply it by the difference of our min/max points ($maxy – $miny) and then add back the minimum point to ensure that we never go below that. Do this for each of the X and Y coordinates.

Now let’s create a function to check if our random coordinate is within our bounds. We’ll need to do two things:

  • Loop over each given point and the given point before it in the list
  • Check if our random point is within the bounds of each of those two points

This will loop over our points array and do a simple check to make sure our point is within the min/maxes of the two given points. The next check is a little more messy.

This post from StackOverflow explains the math for this one better than I ever could. The above is adapted from there. If it passes both of these test, we’ve found our lucky point. If not, reset the testing points and try again.

Putting it all together

Now that we have the basic idea, we can put it all together.

And here are a few sample runs:

The four random points

Leave a Reply

Your email address will not be published. Required fields are marked *