How to Create a GeoJSON File Using Python

In this tutorial, we will teach you how to create a GeoJSON file using Python. GeoJSON is a popular geospatial data format, widely used in various sorts of applications ranging from web mapping to data science. Python, having a rich set of libraries, makes the task of creating and manipulating GeoJSON data trouble-free.

Step 1: Install Necessary Libraries

The first step in our task is to install the necessary Python libraries. We will be using the geopandas and json library in this tutorial. You can install it via pip:

Step 2: Load Geospatial Data

Load the geospatial data into a GeoPandas dataframe using the read_file method. For this tutorial, we will use sample data from the Natural Earth site. Download the shapefile for countries from the site and load it in Python:

Apart from the “shp” file, you also should copy the “shx” file located in the same directory.

Step 3: Convert Data to GeoJSON Format

Now convert the loaded data to GeoJSON format:

Step 4: Write GeoJSON Data to a file

Finally, write the GeoJSON data to a file using the json library:

Now you have a GeoJSON file ‘countries.geojson’ containing polygon geometries for all countries.

Full Code:

Conclusion

Creating a GeoJSON file is straightforward in Python due to its rich set of libraries. Adapting this tutorial to your usage should set you on the right path to manipulating and leveraging GeoJSON for your projects.