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:
1 |
pip install geopandas |
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:
1 2 |
import geopandas as gpd gdf = gpd.read_file('ne_110m_admin_0_countries.shp') |
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:
1 |
geojson_data = gdf.__geo_interface__ |
Step 4: Write GeoJSON Data to a file
Finally, write the GeoJSON data to a file using the json library:
1 2 3 |
import json with open('countries.geojson', 'w') as f: json.dump(geojson_data, f) |
Now you have a GeoJSON file ‘countries.geojson’ containing polygon geometries for all countries.
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 |
import geopandas as gpd import json # read geospatial data gdf = gpd.read_file('ne_110m_admin_0_countries.shp') # convert to GeoJSON geojson_data = gdf.__geo_interface__ # write GeoJSON data to a file with open('countries.geojson', 'w') as f: json.dump(geojson_data, f) |
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.