1

I am trying to use the following GeoJson file

On my server and via php I would like to be able to call a url, perhaps: http://example.com/point.php?country=Argentina and then 1 random point would ouput.

I understand that the geojson file marks the boundaries of each country. What is the best way to do this?

I have googled and also looked for examples or ideas via stackoverflow without much luck which is why I am posting. I have been able to do this with just the USA by state but I would really like to use this geojson file as it would be more accurate and enable me to generate a random point from any specified country. The included code works for the states. I'd like to modify it to work with this geojson file.

"AK": {
    "name": "Alaska",
    "min_lat": 52.5964,
    "max_lat": 71.5232,
    "min_lng": -169.9146,
    "max_lng": -129.993
}

<?php
function float_rand($Min, $Max){
    if ($Min > $Max) {
        $min = $Max;
        $max = $Min;
    } else {
        $min = $Min;
        $max = $Max;
    }
    $randomfloat = $min + mt_rand() / mt_getrandmax() * ($max - $min);
    $randomfloat = round($randomfloat, 14);

    return $randomfloat;
}

$boundaries_json = file_get_contents("state_boundaries.json");
$boundaries = json_decode($boundaries_json, true);

$b = array();
foreach ($boundaries as $state => $bounds) {
    $b[] = $bounds;
}

$state = $b[rand(0, sizeof($b) - 1)];

//print_r($state);

// generate coords
$lat = float_rand($state["min_lat"], $state["max_lat"]);
$lon = float_rand($state["min_lng"], $state["max_lng"]);

The included code works for the states. I'd like to modify it to work with this geojson file.

Alessandro Lodi
  • 544
  • 1
  • 4
  • 14
Paul
  • 64
  • 7
  • 1
    The code you have provided seems to operate on a very simplified view of the states, assuming that each state forms a perfect rectangle. The co-ordinates provided for Alaska do provide all points inside Alaska, but also include points in Canada and Russia. This may be ok for your use case, but the geojson file that you have linked gives the actual outline of the countries, rather than the rectangle that encompasses them. To use this file would need a much more complex algorithm than the one you are currently using. Look at http://alienryderflex.com/polygon/ as a possible starting point – Matt Garrod Feb 07 '19 at 20:15

1 Answers1

1

Your code gets coordinates in a rectangular area.

If you get a coordinate you have to check if your point is in the boundary of the state, that is an irregular polygon

(To check if a point is inside a polygon you can see here)

At this point you have two choices:

  1. Generate points inside a rectangle that circumscribes the boundary until one point is in your polygon

  2. Decompose your polygon into triangles and then generate a random point in those triangles

Argentina coordinate example

Nick
  • 138,499
  • 22
  • 57
  • 95
Alessandro Lodi
  • 544
  • 1
  • 4
  • 14