Tuesday, November 1, 2016

GeoJSON in Python


Few days ago, I wrote a blog post on using QGIS to convert a Shapefile to GeoJSON.

In this post, I will talk about working with GeoJSON object in Python programming language.

Basically we know a GeoJSON is an object contains spatially related datasets. Conventions used by GeoJSON are known to programmers, which include C, C++, Java, Python, Perl, etc.

GeoJSON has the benefit of having implementations in many languages (especially JavaScript), making it suitable for inter-application communication of spatial data.

GeoJSON in Python

There are many python libraries that allow you to load and manipulate JSON/GeoJSON objects within the python programming ecosystem. The common and default library is the JSON which comes by default with any python installation.

All you need to do to use it is to call this line "import json".

Code Demo

Am going to use a GeoJSON file containing polygon features and saved with the name "Polygon_3.geojson" on my local disk for this demonstration.

There are two most important functions in the json library for converting python objects to json/geojson or vise-versa named: dumps() and load() functions.

In this demo, I will just read in the geojson file above into the python development environment using the with open() python command. This will allow us have access to the individual polygon elements within the geojson file as follow:-

.As you can see from above, when you load a GeoJSON file using the JSON library, you get a dictionary that contains an entry features, which contains the list of features.

Each feature in turn consists of a dictionary, which among other things, contains an entry geometry.

The geometry is a dictionary containing the entries type (polygon in this case) and coordinates of the vertices. So you can traverse the GeoJSON file like this:

import json

with open('Polygon_3.geojson') as f:
    data = json.load(f)

for feature in data['features']:
    print (feature['geometry']['type'])
    print (feature['geometry']['coordinates'])

As you can see, the GeoJSON file contains five polygons of different number of vertices and shape as indicated by the amount of pairs of coordinates for each polygon.

That is it.
Thanks for reading.

No comments:

Post a Comment