Building a GeoJSON with Python

There is the python-geojson library (https://github.com/frewsxcv/python-geojson), which seems to make this task also much easier. Example from the library page:

>>> from geojson import Polygon

>>> Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38,   57.322)]])  
{"coordinates": [[[2.3..., 57.32...], [23.19..., -20.2...], [-120.4..., 19.1...]]], "type": "Polygon"}

If you can get the libraries installed, django has some good tools for dealing with geometry objects, and these objects have a geojson attribute, giving you access to the GeoJSON representation of the object:

https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/

>>> from django.contrib.gis.geos import Polygon, Point, MultiPoint, GeometryCollection
>>>
>>> poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
>>> gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)
>>> gc.geojson
u'{ "type": "GeometryCollection", "geometries": [ { "type": "Point", "coordinates": [ 0.0, 0.0 ] }, { "type": "MultiPoint", "coordinates": [ [ 0.0, 0.0 ], [ 1.0, 1.0 ] ] }, { "type": "Polygon", "coordinates": [ [ [ 0.0, 0.0 ], [ 0.0, 1.0 ], [ 1.0, 1.0 ], [ 0.0, 0.0 ] ] ] } ] }'

GeometryCollection can also accept a list of geometry objects:

>>> polys = []
>>> for i in range(5):
...     poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
...     polys.append(poly)
...
>>> gc = GeometryCollection(polys)

Update 2019:

shapely with shapely-geojson is now available can may be more easily to introduce as it doesn't required django.


  1. Since you've already know how to construct a point, it's quite similar to construct a polygon object.
  2. you could use json.dumps to convert a python object to string

Something like:

geos = []
for longs,lats in LongLatList
    poly = {
        'type': 'Polygon',
        'coordinates': [[lon,lat] for lon,lat in zip(longs,lats) ]
    }
    geos.append(poly)

geometries = {
    'type': 'FeatureCollection',
    'features': geos,
}

geo_str = json.dumps(geometries) // import json