Skip to content

Instantly share code, notes, and snippets.

@arbakker
Last active October 4, 2022 11:40
Show Gist options
  • Save arbakker/7f44e6fcfcea2206fb0c860fa4a06e0b to your computer and use it in GitHub Desktop.
Save arbakker/7f44e6fcfcea2206fb0c860fa4a06e0b to your computer and use it in GitHub Desktop.
Generate featurecollection with random points within bounding box and random atttribute values #geojson #python #click #mock #testing
#!/usr/bin/env python3
import os
import json
from pathlib import Path
import random
import uuid
import click
def get_random_word():
"""
relies on linux/ubuntu supplied dictionary of words in /etc/dictionaries/words
"""
return random.choice(
[
x.replace("\n", "")
for x in open("/etc/dictionaries-common/words").readlines()
]
)
def get_random_point(minx, maxx, miny, maxy):
x = round(random.uniform(minx, maxx), 2)
y = round(random.uniform(miny, maxy), 2)
return [x, y]
@click.command()
@click.argument("bbox")
@click.argument("properties")
@click.option("--n", default=100)
@click.option("--output-file")
def main(bbox, properties, n, output_file):
minx, miny, maxx, maxy = [float(x) for x in bbox.split(",")]
fc = {
"type": "FeatureCollection",
"crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::28992"}},
"features": [],
}
for _ in range(0, n):
point = get_random_point(minx, maxx, miny, maxy)
properties_dict = {x: "string" for x in properties.split(",")}
properties_out = {key: get_random_word() for key in properties_dict.keys()}
ft = {
"type": "Feature",
"id": str(uuid.uuid4()),
"properties": properties_out,
"geometry": {"type": "Point", "coordinates": point},
}
fc["features"].append(ft)
output_file = os.path.abspath(output_file)
if output_file and Path(os.path.dirname(output_file)).is_dir():
with open(output_file, "w") as f:
json.dump(fc, f)
elif output_file:
print(f"destination dir does not exist: {os.path.basename(output_file)}")
exit(1)
else:
print(json.dumps(fc, indent=4))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment