Quiero crear mediante programación un archivo GeoJSON usando polígonos de un archivo de forma pero agregando atributos desde mi propia aplicación.
Esto se hace fácilmente para un shapefile:
def create_data_dayer(self,varlist, data):
"""
Creates a new shape to contain data about nodes.
varlist is the list of fields names associated with
the nodes.
data is a list of lists whose first element is the geocode
and the remaining elements are values of the fields, in the
same order as they appear in varlist.
"""
if os.path.exists(os.path.join(self.outdir,'Data.shp')):
os.remove(os.path.join(self.outdir,'Data.shp'))
os.remove(os.path.join(self.outdir,'Data.shx'))
os.remove(os.path.join(self.outdir,'Data.dbf'))
# Creates a new shape file to hold the data
if not self.datasource:
dsd = self.driver.CreateDataSource(os.path.join(self.outdir,'Data.shp'))
self.datasource = dsd
dl = dsd.CreateLayer("sim_results",geom_type=ogr.wkbPolygon)
#Create the fields
fi1 = ogr.FieldDefn("geocode",field_type=ogr.OFTInteger)
dl.CreateField(fi1)
for v in varlist:
#print "creating data fields"
fi = ogr.FieldDefn(v,field_type=ogr.OFTString)
fi.SetPrecision(12)
dl.CreateField(fi)
#Add the features (points)
for n,l in enumerate(data):
#Iterate over the lines of the data matrix.
gc = l[0]
try:
geom = self.geomdict[gc]
if geom.GetGeometryType() != 3: continue
#print geom.GetGeometryCount()
fe = ogr.Feature(dl.GetLayerDefn())
fe.SetField('geocode',gc)
for v,d in zip (varlist,l[1:]):
#print v,d
fe.SetField(v,str(d))
#Add the geometry
#print "cloning geometry"
clone = geom.Clone()
#print geom
#print "setting geometry"
fe.SetGeometry(clone)
#print "creating geom"
dl.CreateFeature(fe)
except: #Geocode not in polygon dictionary
pass
dl.SyncToDisk()
Como tengo todas las geometrías en un diccionario por geocódigo (self.geomdict), simplemente creo las características, configuro los campos y clono las geometrías de la capa preexistente (la carga del código se omitió por simplicidad). Todo lo que necesito ahora es una forma de generar el GeoJSON a partir de la combinación de campos y geometrías, naturalmente con la ayuda de OGR para obtener el resto del archivo correctamente (CRS, etc. a partir del mapa fuente)
¿Cómo exportar la colección de características generada como arriba?

fe.ExportToJson()devuelve una cadena, por lo que debe ajustarsejson.loads(...). De lo contrario, esto es muy útil.Si tiene un entorno de desarrollo GDAL / OGR (encabezados, bibliotecas), puede simplificar radicalmente su código utilizando Fiona . Para leer características de un shapefile, agregue nuevos atributos y escríbalos ya que GeoJSON es solo un puñado de líneas:
fuente
Este es el más simple y fácil en Fiona. puede configurar el SRS para la salida GeoJSON.
fuente