Quantcast
Viewing all articles
Browse latest Browse all 11

Converting JSON to GeoJSON MultiPoint using `ogr.CreateGeometryFromJSON`

I am trying to convert a JSON array to a geom in Python, by first converting it to a GeoJSON.


I have point coordinates in a JSON array,

[{'lat':100.0, 'lng':0.0},{'lat':101.0, 'lng':1.0'}]

that I want to convert to GeoJSON to then use as a geom in Python.

I convert the JSON array using a Python function,

def json2geojson(items):
    import json
    return json.dumps({
            "type": "MultiPoint", "coordinates":[ [ feature['lng'], feature['lat']]
                      for feature in json.loads(items)
            ]})

my_geojson = json2geojson(my_json)

which gives me this:

{ "type": "MultiPoint",
    "coordinates": [ [100.0, 0.0], [101.0, 1.0] ]
    }

Then I try to convert a geometry from the GeoJSON,

from osgeo import ogr

geom = ogr.CreateGeometryFromJson(my_geojson)

which at first glance appears to work

<osgeo.ogr.Geometry; proxy of <Swig Object of type 'OGRGeometryShadow *' at 0x113ea9ea0> >

however something clearly goes wrong

print "%d,%d" % (geom.GetX(), geom.GetY())
0,0
print "Geometry has %i points" % (geom.GetPointCount())
Geometry has 0 points

Does anyone know why this is not working or the best way to do this type of conversion?


Edit:

Code works for a single point:

from osgeo import ogr

geojson = """{"type":"Point","coordinates":[108420.33,753808.59]}"""
point = ogr.CreateGeometryFromJson(geojson)
print "%d,%d" % (point.GetX(), point.GetY())

From http://pcjericks.github.io/py-gdalogr-cookbook/geometry.html#create-geometry-from-geojson


Viewing all articles
Browse latest Browse all 11

Trending Articles