简体   繁体   中英

Append geoJSON feature with Python?

I have the following structure in a geojsonfile:

{"crs": 
  {"type": "name", 
   "properties": 
     {"name": "urn:ogc:def:crs:EPSG::4326"}
  }, 
   "type": "FeatureCollection", 
   "features": [
     {"geometry": 
       {"type": "Polygon", 
        "coordinates": [[[10.914622377957983, 45.682007076150505],
                         [10.927456267537572, 45.68179119797432], 
                         [10.927147329501077, 45.672795442796335],
                         [10.914315493899755, 45.67301125363092], 
                         [10.914622377957983, 45.682007076150505]]]},           
        "type": "Feature", 
        "id": 0, 
        "properties": {"cellId": 38}
   },
      {"geometry": 
        {"type": "Polygon", 
         "coordinates":
   ... etc. ...

I want to read this geoJSON into Google Maps and have each cell colored based on a property I calculated in Python for each cell individually. So my most question would be: How can I read the geoJSON in with Python and add another property to these Polygons (there are like 12 000 polygons, so adding them one by one is not an option), then write the new file?

I think what I'm looking for is a library for Python that can handle geoJSON, so I don't have to add these feature via srting manipulation.

There is a way with Python geojson package .

Like that, you can read the geojson has an object:

import geojson
loaded = geojson.loads("Any geojson file or geojson string")

for feature in loaded.features[0:50]: #[0:50] for the only first 50th.
    print feature

There is Feature, FeatureCollection and Custom classes to help you to add your attributes.

The geoJSON is just a JSON doc (a simplification but is all you need for this purpose). Python reads that as a dict object.

Since dict are updated inplace, we don't need to store a new variable for the geo objects.

import json

# read in json 
geo_objects = json.load(open("/path/to/files"))

# code ...

for d in geo_objects:
    d["path"]["to"]["field"] = calculated_value

json.dump(geofiles, open("/path/to/output/file"))

No string manipulation needed, no need to load new library!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM