Skip to content

Instantly share code, notes, and snippets.

@jasonbeverage
Created July 11, 2022 14:33
Show Gist options
  • Save jasonbeverage/ca13cde730f61640990f728f861ecf5e to your computer and use it in GitHub Desktop.
Save jasonbeverage/ca13cde730f61640990f728f861ecf5e to your computer and use it in GitHub Desktop.
Generates a mappings.xml file for use with osgEarth CoverageLayer based on unique values in an attribute in a vector file.
from osgeo import ogr
import click
def get_unique_values(layer, field):
"""
Finds all the unique values in the vector layer
"""
layer.ResetReading()
values = set()
for feature in layer:
values.add(feature.GetField(field))
return values
def generate_ids(values):
"""
Given a list of unique values generate a map that maps the string value to
an integer id
"""
ids = {}
id = 0
for v in values:
ids[v] = id
id+=1
return ids
def write_ids(layer, ids, input_field, output_field):
layer.ResetReading()
for feature in layer:
value = feature.GetField(input_field)
id = ids[value]
feature.SetField(output_field, id)
layer.SetFeature(feature)
def write_mapping_file(ids, filename):
with open(filename, 'w') as out:
out.write("<mappings>\n")
for i in ids.items():
out.write(' <mapping value="%s" biome_id="%s"/>\n' % (i[1], i[0]))
out.write("</mappings>")
@click.command()
@click.argument('filename')
@click.option('--input_field', help='The field to generate unique ids for')
@click.option('--output_field', help='The field to write ids to')
def generate_mapping_ids(filename, input_field, output_field):
# Open the dataset for writing
dataset = ogr.Open(filename, 1)
if dataset is None:
print("Couldn't open %s" % filename)
return 0
layer = dataset.GetLayer(0)
# Find all the unique values in the dataset
values = get_unique_values(layer, input_field)
# Generate a map from values to ids
ids = generate_ids(values)
write_ids(layer, ids, input_field, output_field)
write_mapping_file(ids, "mappings.xml")
layer = None
dataset = None
if __name__ == '__main__':
generate_mapping_ids()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment