Python bindings and utilities for GeoJSON

Overview

geojson

GitHub Actions Codecov Jazzband

This Python library contains:

Table of Contents

Installation

geojson is compatible with Python 3.6 - 3.9. The recommended way to install is via pip:

pip install geojson

GeoJSON Objects

This library implements all the GeoJSON Objects described in The GeoJSON Format Specification.

All object keys can also be used as attributes.

The objects contained in GeometryCollection and FeatureCollection can be indexed directly.

Point

>>> from geojson import Point

>>> Point((-115.81, 37.24))  # doctest: +ELLIPSIS
{"coordinates": [-115.8..., 37.2...], "type": "Point"}

Visualize the result of the example above here. General information about Point can be found in Section 3.1.2 and Appendix A: Points within The GeoJSON Format Specification.

MultiPoint

>>> from geojson import MultiPoint

>>> MultiPoint([(-155.52, 19.61), (-156.22, 20.74), (-157.97, 21.46)])  # doctest: +ELLIPSIS
{"coordinates": [[-155.5..., 19.6...], [-156.2..., 20.7...], [-157.9..., 21.4...]], "type": "MultiPoint"}

Visualize the result of the example above here. General information about MultiPoint can be found in Section 3.1.3 and Appendix A: MultiPoints within The GeoJSON Format Specification.

LineString

>>> from geojson import LineString

>>> LineString([(8.919, 44.4074), (8.923, 44.4075)])  # doctest: +ELLIPSIS
{"coordinates": [[8.91..., 44.407...], [8.92..., 44.407...]], "type": "LineString"}

Visualize the result of the example above here. General information about LineString can be found in Section 3.1.4 and Appendix A: LineStrings within The GeoJSON Format Specification.

MultiLineString

>>> from geojson import MultiLineString

>>> MultiLineString([
...     [(3.75, 9.25), (-130.95, 1.52)],
...     [(23.15, -34.25), (-1.35, -4.65), (3.45, 77.95)]
... ])  # doctest: +ELLIPSIS
{"coordinates": [[[3.7..., 9.2...], [-130.9..., 1.52...]], [[23.1..., -34.2...], [-1.3..., -4.6...], [3.4..., 77.9...]]], "type": "MultiLineString"}

Visualize the result of the example above here. General information about MultiLineString can be found in Section 3.1.5 and Appendix A: MultiLineStrings within The GeoJSON Format Specification.

Polygon

>>> from geojson import Polygon

>>> # no hole within polygon
>>> Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])  # doctest: +ELLIPSIS
{"coordinates": [[[2.3..., 57.32...], [23.19..., -20.2...], [-120.4..., 19.1...]]], "type": "Polygon"}

>>> # hole within polygon
>>> Polygon([
...     [(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)],
...     [(-5.21, 23.51), (15.21, -10.81), (-20.51, 1.51), (-5.21, 23.51)]
... ])  # doctest: +ELLIPSIS
{"coordinates": [[[2.3..., 57.32...], [23.19..., -20.2...], [-120.4..., 19.1...]], [[-5.2..., 23.5...], [15.2..., -10.8...], [-20.5..., 1.5...], [-5.2..., 23.5...]]], "type": "Polygon"}

Visualize the results of the example above here. General information about Polygon can be found in Section 3.1.6 and Appendix A: Polygons within The GeoJSON Format Specification.

MultiPolygon

>>> from geojson import MultiPolygon

>>> MultiPolygon([
...     ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)],),
...     ([(23.18, -34.29), (-1.31, -4.61), (3.41, 77.91), (23.18, -34.29)],)
... ])  # doctest: +ELLIPSIS
{"coordinates": [[[[3.7..., 9.2...], [-130.9..., 1.5...], [35.1..., 72.23...]]], [[[23.1..., -34.2...], [-1.3..., -4.6...], [3.4..., 77.9...]]]], "type": "MultiPolygon"}

Visualize the result of the example above here. General information about MultiPolygon can be found in Section 3.1.7 and Appendix A: MultiPolygons within The GeoJSON Format Specification.

GeometryCollection

>>> from geojson import GeometryCollection, Point, LineString

>>> my_point = Point((23.532, -63.12))

>>> my_line = LineString([(-152.62, 51.21), (5.21, 10.69)])

>>> geo_collection = GeometryCollection([my_point, my_line])

>>> geo_collection  # doctest: +ELLIPSIS
{"geometries": [{"coordinates": [23.53..., -63.1...], "type": "Point"}, {"coordinates": [[-152.6..., 51.2...], [5.2..., 10.6...]], "type": "LineString"}], "type": "GeometryCollection"}

>>> geo_collection[1]
{"coordinates": [[-152.62, 51.21], [5.21, 10.69]], "type": "LineString"}

>>> geo_collection[0] == geo_collection.geometries[0]
True

Visualize the result of the example above here. General information about GeometryCollection can be found in Section 3.1.8 and Appendix A: GeometryCollections within The GeoJSON Format Specification.

Feature

>>> from geojson import Feature, Point

>>> my_point = Point((-3.68, 40.41))

>>> Feature(geometry=my_point)  # doctest: +ELLIPSIS
{"geometry": {"coordinates": [-3.68..., 40.4...], "type": "Point"}, "properties": {}, "type": "Feature"}

>>> Feature(geometry=my_point, properties={"country": "Spain"})  # doctest: +ELLIPSIS
{"geometry": {"coordinates": [-3.68..., 40.4...], "type": "Point"}, "properties": {"country": "Spain"}, "type": "Feature"}

>>> Feature(geometry=my_point, id=27)  # doctest: +ELLIPSIS
{"geometry": {"coordinates": [-3.68..., 40.4...], "type": "Point"}, "id": 27, "properties": {}, "type": "Feature"}

Visualize the results of the examples above here. General information about Feature can be found in Section 3.2 within The GeoJSON Format Specification.

FeatureCollection

>>> from geojson import Feature, Point, FeatureCollection

>>> my_feature = Feature(geometry=Point((1.6432, -19.123)))

>>> my_other_feature = Feature(geometry=Point((-80.234, -22.532)))

>>> feature_collection = FeatureCollection([my_feature, my_other_feature])

>>> feature_collection # doctest: +ELLIPSIS
{"features": [{"geometry": {"coordinates": [1.643..., -19.12...], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-80.23..., -22.53...], "type": "Point"}, "properties": {}, "type": "Feature"}], "type": "FeatureCollection"}

>>> feature_collection.errors()
[]

>>> (feature_collection[0] == feature_collection['features'][0], feature_collection[1] == my_other_feature)
(True, True)

Visualize the result of the example above here. General information about FeatureCollection can be found in Section 3.3 within The GeoJSON Format Specification.

GeoJSON encoding/decoding

All of the GeoJSON Objects implemented in this library can be encoded and decoded into raw GeoJSON with the geojson.dump, geojson.dumps, geojson.load, and geojson.loads functions. Note that each of these functions is a wrapper around the core json function with the same name, and will pass through any additional arguments. This allows you to control the JSON formatting or parsing behavior with the underlying core json functions.

>>> import geojson

>>> my_point = geojson.Point((43.24, -1.532))

>>> my_point  # doctest: +ELLIPSIS
{"coordinates": [43.2..., -1.53...], "type": "Point"}

>>> dump = geojson.dumps(my_point, sort_keys=True)

>>> dump  # doctest: +ELLIPSIS
'{"coordinates": [43.2..., -1.53...], "type": "Point"}'

>>> geojson.loads(dump)  # doctest: +ELLIPSIS
{"coordinates": [43.2..., -1.53...], "type": "Point"}

Custom classes

This encoding/decoding functionality shown in the previous can be extended to custom classes using the interface described by the __geo_interface__ Specification.

>>> import geojson

>>> class MyPoint():
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...
...     @property
...     def __geo_interface__(self):
...         return {'type': 'Point', 'coordinates': (self.x, self.y)}

>>> point_instance = MyPoint(52.235, -19.234)

>>> geojson.dumps(point_instance, sort_keys=True)  # doctest: +ELLIPSIS
'{"coordinates": [52.23..., -19.23...], "type": "Point"}'

Default and custom precision

GeoJSON Object-based classes in this package have an additional precision attribute which rounds off coordinates to 6 decimal places (roughly 0.1 meters) by default and can be customized per object instance.

>>> from geojson import Point

>>> Point((-115.123412341234, 37.123412341234))  # rounded to 6 decimal places by default
{"coordinates": [-115.123412, 37.123412], "type": "Point"}

>>> Point((-115.12341234, 37.12341234), precision=8)  # rounded to 8 decimal places
{"coordinates": [-115.12341234, 37.12341234], "type": "Point"}

Helpful utilities

coords

geojson.utils.coords yields all coordinate tuples from a geometry or feature object.

>>> import geojson

>>> my_line = LineString([(-152.62, 51.21), (5.21, 10.69)])

>>> my_feature = geojson.Feature(geometry=my_line)

>>> list(geojson.utils.coords(my_feature))  # doctest: +ELLIPSIS
[(-152.62..., 51.21...), (5.21..., 10.69...)]

map_coords

geojson.utils.map_coords maps a function over all coordinate values and returns a geometry of the same type. Useful for scaling a geometry.

>>> import geojson

>>> new_point = geojson.utils.map_coords(lambda x: x/2, geojson.Point((-115.81, 37.24)))

>>> geojson.dumps(new_point, sort_keys=True)  # doctest: +ELLIPSIS
'{"coordinates": [-57.905..., 18.62...], "type": "Point"}'

map_tuples

geojson.utils.map_tuples maps a function over all coordinates and returns a geometry of the same type. Useful for changing coordinate order or applying coordinate transforms.

>>> import geojson

>>> new_point = geojson.utils.map_tuples(lambda c: (c[1], c[0]), geojson.Point((-115.81, 37.24)))

>>> geojson.dumps(new_point, sort_keys=True)  # doctest: +ELLIPSIS
'{"coordinates": [37.24..., -115.81], "type": "Point"}'

map_geometries

geojson.utils.map_geometries maps a function over each geometry in the input.

>>> import geojson

>>> new_point = geojson.utils.map_geometries(lambda g: geojson.MultiPoint([g["coordinates"]]), geojson.GeometryCollection([geojson.Point((-115.81, 37.24))]))

>>> geojson.dumps(new_point, sort_keys=True)
'{"geometries": [{"coordinates": [[-115.81, 37.24]], "type": "MultiPoint"}], "type": "GeometryCollection"}'

validation

is_valid property provides simple validation of GeoJSON objects.

>>> import geojson

>>> obj = geojson.Point((-3.68,40.41,25.14,10.34))
>>> obj.is_valid
False

errors method provides collection of errors when validation GeoJSON objects.

>>> import geojson

>>> obj = geojson.Point((-3.68,40.41,25.14,10.34))
>>> obj.errors()
'a position must have exactly 2 or 3 values'

generate_random

geojson.utils.generate_random yields a geometry type with random data

>>> import geojson

>>> geojson.utils.generate_random("LineString")  # doctest: +ELLIPSIS
{"coordinates": [...], "type": "LineString"}

>>> geojson.utils.generate_random("Polygon")  # doctest: +ELLIPSIS
{"coordinates": [...], "type": "Polygon"}

Development

To build this project, run python setup.py build. To run the unit tests, run python setup.py test. To run the style checks, run flake8 (install flake8 if needed).

Credits

๐ŸŒ Local tile server for viewing geospatial raster files with ipyleaflet or folium

๐ŸŒ Local Tile Server for Geospatial Rasters Need to visualize a rather large (gigabytes) raster you have locally? This is for you. A Flask application

Bane Sullivan 192 Jan 04, 2023
Introduction to Geospatial Analysis in Python

Introduction to Geospatial Analysis in Python This repository is in support of a talk on geospatial data. Data To recreate all of the examples, the da

Dillon Gardner 6 Oct 19, 2022
Daily social mapping project in November 2021. Maps made using PyGMT whenever possible.

Daily social mapping project in November 2021. Maps made using PyGMT whenever possible.

Wei Ji 20 Nov 24, 2022
Platform for building statistical models of cities and regions

UrbanSim UrbanSim is a platform for building statistical models of cities and regions. These models help forecast long-range patterns in real estate d

Urban Data Science Toolkit 419 Dec 30, 2022
Open Data Cube analyses continental scale Earth Observation data through time

Open Data Cube Core Overview The Open Data Cube Core provides an integrated gridded data analysis environment for decades of analysis ready earth obse

Open Data Cube 410 Dec 13, 2022
A ready-to-use curated list of Spectral Indices for Remote Sensing applications.

A ready-to-use curated list of Spectral Indices for Remote Sensing applications. GitHub: https://github.com/davemlz/awesome-ee-spectral-indices Docume

David Montero Loaiza 488 Jan 03, 2023
Python renderer for OpenStreetMap with custom icons intended to display as many map features as possible

Map Machine project consists of Python OpenStreetMap renderer: SVG map generation, SVG and PNG tile generation, Rรถntgen icon set: unique CC-BY 4.0 map

Sergey Vartanov 0 Dec 18, 2022
GetOSM is an OpenStreetMap tile downloader written in Python that is agnostic of GUI frameworks.

GetOSM GetOSM is an OpenStreetMap tile downloader written in Python that is agnostic of GUI frameworks. It is used with tkinter by ProjPicker. Require

Huidae Cho 3 May 20, 2022
๐ŸŒ Local tile server for viewing geospatial raster files with ipyleaflet

๐ŸŒ Local Tile Server for Geospatial Rasters Need to visualize a rather large raster (gigabytes) you have locally? This is for you. A Flask application

Bane Sullivan 192 Jan 04, 2023
Geographic add-ons for Django REST Framework. Maintained by the OpenWISP Project.

Geographic add-ons for Django REST Framework. Maintained by the OpenWISP Project.

OpenWISP 982 Jan 06, 2023
Processing and interpolating spatial data with a twist of machine learning

Documentation | Documentation (dev version) | Contact | Part of the Fatiando a Terra project About Verde is a Python library for processing spatial da

Fatiando a Terra 468 Dec 20, 2022
A modern, geometric typeface by @chrismsimpson (last commit @ 85fa625 Jun 9, 2020 before deletion)

Metropolis A modern, geometric typeface. Influenced by other popular geometric, minimalist sans-serif typefaces of the new millenium. Designed for opt

Darius 183 Dec 25, 2022
python toolbox for visualizing geographical data and making maps

geoplotlib is a python toolbox for visualizing geographical data and making maps data = read_csv('data/bus.csv') geoplotlib.dot(data) geoplotlib.show(

Andrea Cuttone 976 Dec 11, 2022
ESMAC diags - Earth System Model Aerosol-Cloud Diagnostics Package

Earth System Model Aerosol-Cloud Diagnostics Package This Earth System Model (ES

Pacific Northwest National Laboratory 1 Jan 04, 2022
3D extension built off of shapely to make working with geospatial/trajectory data easier in python.

PyGeoShape 3D extension to shapely and pyproj to make working with geospatial/trajectory data easier in python. Getting Started Installation pip The e

Marc Brittain 5 Dec 27, 2022
This is the antenna performance plotted from tinyGS reception data.

tinyGS-antenna-map This is the antenna performance plotted from tinyGS reception data. See their repository. The code produces a plot that provides Az

Martin J. Levy 14 Aug 21, 2022
Django model field that can hold a geoposition, and corresponding widget

django-geoposition A model field that can hold a geoposition (latitude/longitude), and corresponding admin/form widget. Prerequisites Starting with ve

Philipp Bosch 324 Oct 17, 2022
GebPy is a Python-based, open source tool for the generation of geological data of minerals, rocks and complete lithological sequences.

GebPy is a Python-based, open source tool for the generation of geological data of minerals, rocks and complete lithological sequences. The data can be generated randomly or with respect to user-defi

Maximilian Beeskow 16 Nov 29, 2022
Tool to suck data from ArcGIS Server and spit it into PostgreSQL

chupaESRI About ChupaESRI is a Python module/command line tool to extract features from ArcGIS Server map services. Name? Think "chupacabra" or "Chupa

John Reiser 34 Dec 04, 2022
A short term landscape evolution using a path sampling method to solve water and sediment flow continuity equations and model mass flows over complex topographies.

r.sim.terrain A short-term landscape evolution model that simulates topographic change for both steady state and dynamic flow regimes across a range o

Brendan Harmon 7 Oct 21, 2022