Generating GeoJSON with Python The Next CEO of Stack OverflowGDAL and Python: How to get coordinates for all cells having a specific value?Looking for GeoJSON describing French departments?Geometry workflow from Shapely to GeoJSONWhere to find GeoJSON data for the UK?Writing geoJson from rasterstatsConverting shapes in a personal geodatabase to GeoJSONHow to import DGN geometry into a file geodatabase?OGR CreateLayer returns TypeErrorAdd joined data in fiona with new schemaFilter geojson or shapefilesWhy is feature.geometry() None in my user-defined expression function?How to correctly import GeoJSON in PostGIS?Obtaining shape or width of road in GeoJSON format?Using SET methods when feature classes setup in GDB using python, comtypes, ArcObjects?Getting polygons out of multi-polygon GeoJSON files?Set or change the geometry type of an empty point shapefile using Python with GDAL/OGR
Reference request: Grassmannian and Plucker coordinates in type B, C, D
Easy to read palindrome checker
Help/tips for a first time writer?
Inexact numbers as keys in Association?
Is there an equivalent of cd - for cp or mv
Is it professional to write unrelated content in an almost-empty email?
Physiological effects of huge anime eyes
Would a grinding machine be a simple and workable propulsion system for an interplanetary spacecraft?
Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis
Can I board the first leg of the flight without having final country's visa?
Why doesn't UK go for the same deal Japan has with EU to resolve Brexit?
Getting Stale Gas Out of a Gas Tank w/out Dropping the Tank
How many extra stops do monopods offer for tele photographs?
Can I use the word “Senior” as part of a job title directly in German?
Defamation due to breach of confidentiality
"Eavesdropping" vs "Listen in on"
0-rank tensor vs vector in 1D
How to properly draw diagonal line while using multicolumn inside tabular environment?
If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?
Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?
What does "shotgun unity" refer to here in this sentence?
Regression vs Random Forest - Combination of features
Is it ever safe to open a suspicious HTML file (e.g. email attachment)?
Is it convenient to ask the journal's editor for two additional days to complete a review?
Generating GeoJSON with Python
The Next CEO of Stack OverflowGDAL and Python: How to get coordinates for all cells having a specific value?Looking for GeoJSON describing French departments?Geometry workflow from Shapely to GeoJSONWhere to find GeoJSON data for the UK?Writing geoJson from rasterstatsConverting shapes in a personal geodatabase to GeoJSONHow to import DGN geometry into a file geodatabase?OGR CreateLayer returns TypeErrorAdd joined data in fiona with new schemaFilter geojson or shapefilesWhy is feature.geometry() None in my user-defined expression function?How to correctly import GeoJSON in PostGIS?Obtaining shape or width of road in GeoJSON format?Using SET methods when feature classes setup in GDB using python, comtypes, ArcObjects?Getting polygons out of multi-polygon GeoJSON files?Set or change the geometry type of an empty point shapefile using Python with GDAL/OGR
I want to programmatically create a GeoJSON file using polygons from a shapefile but adding attributes from my own application.
This is easily done for a 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()
since I have all the geometries on a dictionary by geocode (self.geomdict) I simply create the features, set the fields and clone the geometries from pre-existing layer (code loading that layer omitted for simplicity). All I need now is a way to generate the GeoJSON from the combination of fields and geometries, naturally with the help of OGR to get the rest of the file right (CRS, etc. as from the source map)
How do export the feature collection generated as above?
python geojson ogr fiona
add a comment |
I want to programmatically create a GeoJSON file using polygons from a shapefile but adding attributes from my own application.
This is easily done for a 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()
since I have all the geometries on a dictionary by geocode (self.geomdict) I simply create the features, set the fields and clone the geometries from pre-existing layer (code loading that layer omitted for simplicity). All I need now is a way to generate the GeoJSON from the combination of fields and geometries, naturally with the help of OGR to get the rest of the file right (CRS, etc. as from the source map)
How do export the feature collection generated as above?
python geojson ogr fiona
add a comment |
I want to programmatically create a GeoJSON file using polygons from a shapefile but adding attributes from my own application.
This is easily done for a 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()
since I have all the geometries on a dictionary by geocode (self.geomdict) I simply create the features, set the fields and clone the geometries from pre-existing layer (code loading that layer omitted for simplicity). All I need now is a way to generate the GeoJSON from the combination of fields and geometries, naturally with the help of OGR to get the rest of the file right (CRS, etc. as from the source map)
How do export the feature collection generated as above?
python geojson ogr fiona
I want to programmatically create a GeoJSON file using polygons from a shapefile but adding attributes from my own application.
This is easily done for a 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()
since I have all the geometries on a dictionary by geocode (self.geomdict) I simply create the features, set the fields and clone the geometries from pre-existing layer (code loading that layer omitted for simplicity). All I need now is a way to generate the GeoJSON from the combination of fields and geometries, naturally with the help of OGR to get the rest of the file right (CRS, etc. as from the source map)
How do export the feature collection generated as above?
python geojson ogr fiona
python geojson ogr fiona
edited Aug 3 '17 at 1:30
PolyGeo♦
53.8k1781245
53.8k1781245
asked Nov 19 '12 at 9:30
fccoelhofccoelho
4902719
4902719
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
Happily OGR can do this for you as both ogr.Feature and ogr.Geometry objects have ExportToJson() methods. In your code;
fe.ExportToJson()
And since geojson FeatureCollection objects are simply dictionaries with a type of FeatureCollection and a features object containing a list of Feature objects.
feature_collection = "type": "FeatureCollection",
"features": []
feature_collection["features"].append(fe.ExportToJson())
The CRS object in a feature collection can be one of two types:
- A named CRS (e.g. an OGC URN or an EPSG code)
- A link object with a URI and a type such as "proj4"
Depending on your data format it's quite likely that the name is going to be a pain to get from OGR. Instead if we write the projection to a file on disk which we can reference with the URI. We can grab the projection from the layer object (which has several Export functions)
spatial_reference = dl.GetSpatialRef()
with open("data.crs", "wb") as f:
f.write(spatial_reference.ExportToProj4())
feature_collection["crs"] = "type": "link",
"properties":
"href": "data.crs",
"type": "proj4"
This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies
– fccoelho
Nov 22 '12 at 15:42
I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.
– fccoelho
Nov 24 '12 at 21:35
I don't know if functionality has changed since, butfe.ExportToJson()returns a string, so you need to wrap in withjson.loads(...). Otherwise, this is super helpful!
– jon_two
May 4 '18 at 16:44
add a comment |
If you've got an GDAL/OGR dev environment (headers, libs), you could radically simplify your code by using Fiona. To read features from a shapefile, add new attributes, and write them out as GeoJSON is just a handful of lines:
import fiona
import json
features = []
crs = None
with fiona.collection("docs/data/test_uk.shp", "r") as source:
for feat in source:
feat['properties'].update(...) # with your attributes
features.append(feat)
crs = " ".join("+%s=%s" % (k,v) for k,v in source.crs.items())
my_layer =
"type": "FeatureCollection",
"features": features,
"crs":
"type": "link",
"properties": "href": "my_layer.crs", "type": "proj4"
with open("my_layer.json", "w") as f:
f.write(json.dumps(my_layer))
with open("my_layer.crs", "w") as f:
f.write(crs)
4
Fiona docs are killer!
– Chad Cooper
Nov 20 '12 at 16:40
Would vote up more than once if I could!
– om_henners
Nov 20 '12 at 23:26
Isn't there a way to include the crs definition in GeoJSON?
– fccoelho
Nov 22 '12 at 15:41
add a comment |
This is the simplest and easiest one in Fiona. you can set the SRS for output GeoJSON.
import fiona
from fiona.crs import from_epsg
source= fiona.open('shp/second_shp.shp', 'r', encoding = 'utf-8')
with fiona.open('tool_shp_geojson/geojson_fiona.json','w', driver ="GeoJSON", schema=source.schema, encoding = 'utf-8', crs=fiona.crs.from_epsg(4326)) as geojson:
geojson.write(feat)
add a comment |
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "79"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f41465%2fgenerating-geojson-with-python%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Happily OGR can do this for you as both ogr.Feature and ogr.Geometry objects have ExportToJson() methods. In your code;
fe.ExportToJson()
And since geojson FeatureCollection objects are simply dictionaries with a type of FeatureCollection and a features object containing a list of Feature objects.
feature_collection = "type": "FeatureCollection",
"features": []
feature_collection["features"].append(fe.ExportToJson())
The CRS object in a feature collection can be one of two types:
- A named CRS (e.g. an OGC URN or an EPSG code)
- A link object with a URI and a type such as "proj4"
Depending on your data format it's quite likely that the name is going to be a pain to get from OGR. Instead if we write the projection to a file on disk which we can reference with the URI. We can grab the projection from the layer object (which has several Export functions)
spatial_reference = dl.GetSpatialRef()
with open("data.crs", "wb") as f:
f.write(spatial_reference.ExportToProj4())
feature_collection["crs"] = "type": "link",
"properties":
"href": "data.crs",
"type": "proj4"
This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies
– fccoelho
Nov 22 '12 at 15:42
I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.
– fccoelho
Nov 24 '12 at 21:35
I don't know if functionality has changed since, butfe.ExportToJson()returns a string, so you need to wrap in withjson.loads(...). Otherwise, this is super helpful!
– jon_two
May 4 '18 at 16:44
add a comment |
Happily OGR can do this for you as both ogr.Feature and ogr.Geometry objects have ExportToJson() methods. In your code;
fe.ExportToJson()
And since geojson FeatureCollection objects are simply dictionaries with a type of FeatureCollection and a features object containing a list of Feature objects.
feature_collection = "type": "FeatureCollection",
"features": []
feature_collection["features"].append(fe.ExportToJson())
The CRS object in a feature collection can be one of two types:
- A named CRS (e.g. an OGC URN or an EPSG code)
- A link object with a URI and a type such as "proj4"
Depending on your data format it's quite likely that the name is going to be a pain to get from OGR. Instead if we write the projection to a file on disk which we can reference with the URI. We can grab the projection from the layer object (which has several Export functions)
spatial_reference = dl.GetSpatialRef()
with open("data.crs", "wb") as f:
f.write(spatial_reference.ExportToProj4())
feature_collection["crs"] = "type": "link",
"properties":
"href": "data.crs",
"type": "proj4"
This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies
– fccoelho
Nov 22 '12 at 15:42
I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.
– fccoelho
Nov 24 '12 at 21:35
I don't know if functionality has changed since, butfe.ExportToJson()returns a string, so you need to wrap in withjson.loads(...). Otherwise, this is super helpful!
– jon_two
May 4 '18 at 16:44
add a comment |
Happily OGR can do this for you as both ogr.Feature and ogr.Geometry objects have ExportToJson() methods. In your code;
fe.ExportToJson()
And since geojson FeatureCollection objects are simply dictionaries with a type of FeatureCollection and a features object containing a list of Feature objects.
feature_collection = "type": "FeatureCollection",
"features": []
feature_collection["features"].append(fe.ExportToJson())
The CRS object in a feature collection can be one of two types:
- A named CRS (e.g. an OGC URN or an EPSG code)
- A link object with a URI and a type such as "proj4"
Depending on your data format it's quite likely that the name is going to be a pain to get from OGR. Instead if we write the projection to a file on disk which we can reference with the URI. We can grab the projection from the layer object (which has several Export functions)
spatial_reference = dl.GetSpatialRef()
with open("data.crs", "wb") as f:
f.write(spatial_reference.ExportToProj4())
feature_collection["crs"] = "type": "link",
"properties":
"href": "data.crs",
"type": "proj4"
Happily OGR can do this for you as both ogr.Feature and ogr.Geometry objects have ExportToJson() methods. In your code;
fe.ExportToJson()
And since geojson FeatureCollection objects are simply dictionaries with a type of FeatureCollection and a features object containing a list of Feature objects.
feature_collection = "type": "FeatureCollection",
"features": []
feature_collection["features"].append(fe.ExportToJson())
The CRS object in a feature collection can be one of two types:
- A named CRS (e.g. an OGC URN or an EPSG code)
- A link object with a URI and a type such as "proj4"
Depending on your data format it's quite likely that the name is going to be a pain to get from OGR. Instead if we write the projection to a file on disk which we can reference with the URI. We can grab the projection from the layer object (which has several Export functions)
spatial_reference = dl.GetSpatialRef()
with open("data.crs", "wb") as f:
f.write(spatial_reference.ExportToProj4())
feature_collection["crs"] = "type": "link",
"properties":
"href": "data.crs",
"type": "proj4"
answered Nov 19 '12 at 10:32
om_hennersom_henners
13.4k23375
13.4k23375
This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies
– fccoelho
Nov 22 '12 at 15:42
I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.
– fccoelho
Nov 24 '12 at 21:35
I don't know if functionality has changed since, butfe.ExportToJson()returns a string, so you need to wrap in withjson.loads(...). Otherwise, this is super helpful!
– jon_two
May 4 '18 at 16:44
add a comment |
This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies
– fccoelho
Nov 22 '12 at 15:42
I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.
– fccoelho
Nov 24 '12 at 21:35
I don't know if functionality has changed since, butfe.ExportToJson()returns a string, so you need to wrap in withjson.loads(...). Otherwise, this is super helpful!
– jon_two
May 4 '18 at 16:44
This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies
– fccoelho
Nov 22 '12 at 15:42
This is a good solution, because it doesn't add an extra dependency to my project like the (nice) solution of @sgillies
– fccoelho
Nov 22 '12 at 15:42
I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.
– fccoelho
Nov 24 '12 at 21:35
I jus finished my testing with this solution and it worked nicely. However I had to handle manually when features had unicode characters in field names, since ogr.py didn't handle them properly.
– fccoelho
Nov 24 '12 at 21:35
I don't know if functionality has changed since, but
fe.ExportToJson() returns a string, so you need to wrap in with json.loads(...). Otherwise, this is super helpful!– jon_two
May 4 '18 at 16:44
I don't know if functionality has changed since, but
fe.ExportToJson() returns a string, so you need to wrap in with json.loads(...). Otherwise, this is super helpful!– jon_two
May 4 '18 at 16:44
add a comment |
If you've got an GDAL/OGR dev environment (headers, libs), you could radically simplify your code by using Fiona. To read features from a shapefile, add new attributes, and write them out as GeoJSON is just a handful of lines:
import fiona
import json
features = []
crs = None
with fiona.collection("docs/data/test_uk.shp", "r") as source:
for feat in source:
feat['properties'].update(...) # with your attributes
features.append(feat)
crs = " ".join("+%s=%s" % (k,v) for k,v in source.crs.items())
my_layer =
"type": "FeatureCollection",
"features": features,
"crs":
"type": "link",
"properties": "href": "my_layer.crs", "type": "proj4"
with open("my_layer.json", "w") as f:
f.write(json.dumps(my_layer))
with open("my_layer.crs", "w") as f:
f.write(crs)
4
Fiona docs are killer!
– Chad Cooper
Nov 20 '12 at 16:40
Would vote up more than once if I could!
– om_henners
Nov 20 '12 at 23:26
Isn't there a way to include the crs definition in GeoJSON?
– fccoelho
Nov 22 '12 at 15:41
add a comment |
If you've got an GDAL/OGR dev environment (headers, libs), you could radically simplify your code by using Fiona. To read features from a shapefile, add new attributes, and write them out as GeoJSON is just a handful of lines:
import fiona
import json
features = []
crs = None
with fiona.collection("docs/data/test_uk.shp", "r") as source:
for feat in source:
feat['properties'].update(...) # with your attributes
features.append(feat)
crs = " ".join("+%s=%s" % (k,v) for k,v in source.crs.items())
my_layer =
"type": "FeatureCollection",
"features": features,
"crs":
"type": "link",
"properties": "href": "my_layer.crs", "type": "proj4"
with open("my_layer.json", "w") as f:
f.write(json.dumps(my_layer))
with open("my_layer.crs", "w") as f:
f.write(crs)
4
Fiona docs are killer!
– Chad Cooper
Nov 20 '12 at 16:40
Would vote up more than once if I could!
– om_henners
Nov 20 '12 at 23:26
Isn't there a way to include the crs definition in GeoJSON?
– fccoelho
Nov 22 '12 at 15:41
add a comment |
If you've got an GDAL/OGR dev environment (headers, libs), you could radically simplify your code by using Fiona. To read features from a shapefile, add new attributes, and write them out as GeoJSON is just a handful of lines:
import fiona
import json
features = []
crs = None
with fiona.collection("docs/data/test_uk.shp", "r") as source:
for feat in source:
feat['properties'].update(...) # with your attributes
features.append(feat)
crs = " ".join("+%s=%s" % (k,v) for k,v in source.crs.items())
my_layer =
"type": "FeatureCollection",
"features": features,
"crs":
"type": "link",
"properties": "href": "my_layer.crs", "type": "proj4"
with open("my_layer.json", "w") as f:
f.write(json.dumps(my_layer))
with open("my_layer.crs", "w") as f:
f.write(crs)
If you've got an GDAL/OGR dev environment (headers, libs), you could radically simplify your code by using Fiona. To read features from a shapefile, add new attributes, and write them out as GeoJSON is just a handful of lines:
import fiona
import json
features = []
crs = None
with fiona.collection("docs/data/test_uk.shp", "r") as source:
for feat in source:
feat['properties'].update(...) # with your attributes
features.append(feat)
crs = " ".join("+%s=%s" % (k,v) for k,v in source.crs.items())
my_layer =
"type": "FeatureCollection",
"features": features,
"crs":
"type": "link",
"properties": "href": "my_layer.crs", "type": "proj4"
with open("my_layer.json", "w") as f:
f.write(json.dumps(my_layer))
with open("my_layer.crs", "w") as f:
f.write(crs)
answered Nov 20 '12 at 16:22
sgilliessgillies
6,79312023
6,79312023
4
Fiona docs are killer!
– Chad Cooper
Nov 20 '12 at 16:40
Would vote up more than once if I could!
– om_henners
Nov 20 '12 at 23:26
Isn't there a way to include the crs definition in GeoJSON?
– fccoelho
Nov 22 '12 at 15:41
add a comment |
4
Fiona docs are killer!
– Chad Cooper
Nov 20 '12 at 16:40
Would vote up more than once if I could!
– om_henners
Nov 20 '12 at 23:26
Isn't there a way to include the crs definition in GeoJSON?
– fccoelho
Nov 22 '12 at 15:41
4
4
Fiona docs are killer!
– Chad Cooper
Nov 20 '12 at 16:40
Fiona docs are killer!
– Chad Cooper
Nov 20 '12 at 16:40
Would vote up more than once if I could!
– om_henners
Nov 20 '12 at 23:26
Would vote up more than once if I could!
– om_henners
Nov 20 '12 at 23:26
Isn't there a way to include the crs definition in GeoJSON?
– fccoelho
Nov 22 '12 at 15:41
Isn't there a way to include the crs definition in GeoJSON?
– fccoelho
Nov 22 '12 at 15:41
add a comment |
This is the simplest and easiest one in Fiona. you can set the SRS for output GeoJSON.
import fiona
from fiona.crs import from_epsg
source= fiona.open('shp/second_shp.shp', 'r', encoding = 'utf-8')
with fiona.open('tool_shp_geojson/geojson_fiona.json','w', driver ="GeoJSON", schema=source.schema, encoding = 'utf-8', crs=fiona.crs.from_epsg(4326)) as geojson:
geojson.write(feat)
add a comment |
This is the simplest and easiest one in Fiona. you can set the SRS for output GeoJSON.
import fiona
from fiona.crs import from_epsg
source= fiona.open('shp/second_shp.shp', 'r', encoding = 'utf-8')
with fiona.open('tool_shp_geojson/geojson_fiona.json','w', driver ="GeoJSON", schema=source.schema, encoding = 'utf-8', crs=fiona.crs.from_epsg(4326)) as geojson:
geojson.write(feat)
add a comment |
This is the simplest and easiest one in Fiona. you can set the SRS for output GeoJSON.
import fiona
from fiona.crs import from_epsg
source= fiona.open('shp/second_shp.shp', 'r', encoding = 'utf-8')
with fiona.open('tool_shp_geojson/geojson_fiona.json','w', driver ="GeoJSON", schema=source.schema, encoding = 'utf-8', crs=fiona.crs.from_epsg(4326)) as geojson:
geojson.write(feat)
This is the simplest and easiest one in Fiona. you can set the SRS for output GeoJSON.
import fiona
from fiona.crs import from_epsg
source= fiona.open('shp/second_shp.shp', 'r', encoding = 'utf-8')
with fiona.open('tool_shp_geojson/geojson_fiona.json','w', driver ="GeoJSON", schema=source.schema, encoding = 'utf-8', crs=fiona.crs.from_epsg(4326)) as geojson:
geojson.write(feat)
answered 2 days ago
Muhammad Imran SiddiqueMuhammad Imran Siddique
1508
1508
add a comment |
add a comment |
Thanks for contributing an answer to Geographic Information Systems Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f41465%2fgenerating-geojson-with-python%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
