• Stars
    star
    876
  • Rank 50,202 (Top 2 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created almost 13 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python bindings and utilities for GeoJSON

geojson

GitHub Actions Codecov Jazzband

This Python library contains:

Table of Contents

Installation

geojson is compatible with Python 3.7 - 3.11. 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), (-120.43, 19.15), (23.194, -20.28), (2.38, 57.322)]])  # doctest: +ELLIPSIS
{"coordinates": [[[2.3..., 57.32...], [-120.4..., 19.1...], [23.19..., -20.2...]]], "type": "Polygon"}

>>> # hole within polygon
>>> Polygon([
...     [(2.38, 57.322), (-120.43, 19.15), (23.194, -20.28), (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...], [-120.4..., 19.1...], [23.19..., -20.2...]], [[-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"}

Precision can be set at the package level by setting geojson.geometry.DEFAULT_PRECISION

>>> import geojson

>>> geojson.geometry.DEFAULT_PRECISION = 5

>>> from geojson import Point

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

After setting the DEFAULT_PRECISION, coordinates will be rounded off to that precision with geojson.load or geojson.loads. Following one of those with geojson.dump is a quick and easy way to scale down the precision of excessively precise, arbitrarily-sized GeoJSON data.

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 -m pip install tox && tox. To run the style checks, run flake8 (install flake8 if needed).

Credits

More Repositories

1

django-debug-toolbar

A configurable set of panels that display various debug information about the current request/response.
Python
7,858
star
2

pip-tools

A set of tools to keep your pinned Python dependencies fresh.
Python
7,398
star
3

tablib

Python Module for Tabular Datasets in XLS, CSV, JSON, YAML, &c.
Python
4,500
star
4

django-silk

Silky smooth profiling for Django
Python
4,210
star
5

djangorestframework-simplejwt

A JSON Web Token authentication plugin for the Django REST Framework.
Python
3,765
star
6

django-taggit

Simple tagging for django
Python
3,205
star
7

django-oauth-toolkit

OAuth2 goodies for the Djangonauts!
Python
3,021
star
8

django-redis

Full featured redis cache backend for Django.
Python
2,773
star
9

django-model-utils

Django model mixins and utilities.
Python
2,577
star
10

django-push-notifications

Send push notifications to mobile devices through GCM or APNS in Django.
Python
2,210
star
11

django-simple-history

Store model history and view/revert changes from admin site.
Python
2,083
star
12

django-widget-tweaks

Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.
Python
2,019
star
13

sorl-thumbnail

Thumbnails for Django
Python
1,717
star
14

django-constance

Dynamic Django settings.
Python
1,643
star
15

django-two-factor-auth

Complete Two-Factor Authentication for Django providing the easiest integration into most Django projects.
Python
1,590
star
16

django-polymorphic

Improved Django model inheritance with automatic downcasting
Python
1,577
star
17

django-pipeline

Pipeline is an asset packaging library for Django.
Python
1,489
star
18

dj-database-url

Use Database URLs in your Django Application.
Python
1,439
star
19

django-axes

Keep track of failed login attempts in Django-powered sites.
Python
1,356
star
20

django-tinymce

TinyMCE integration for Django
JavaScript
1,231
star
21

prettytable

Display tabular data in a visually appealing ASCII table format
Python
1,223
star
22

django-admin2

Extendable, adaptable rewrite of django.contrib.admin
Python
1,182
star
23

django-analytical

Analytics services for Django projects
Python
1,174
star
24

django-smart-selects

chained and grouped selects for django forms
Python
1,094
star
25

django-waffle

A feature flipper for Django
Python
1,075
star
26

django-configurations

A helper for organizing Django project settings by relying on well established programming patterns.
Python
1,067
star
27

django-rest-knox

Authentication Module for django rest auth
Python
1,057
star
28

django-defender

A simple super fast django reusable app that blocks people from brute forcing login attempts
Python
997
star
29

django-auditlog

A Django app that keeps a log of changes made to an object.
Python
990
star
30

django-payments

Universal payment handling for Django.
Python
964
star
31

django-hosts

Dynamic and static host resolving for Django. Maps hostnames to URLconfs.
Python
942
star
32

django-nose

Django test runner using nose
Python
882
star
33

django-dbbackup

Management commands to help backup and restore your project database and media files
Python
879
star
34

django-floppyforms

Full control of form rendering in the templates.
Python
836
star
35

django-newsletter

An email newsletter application for the Django web application framework, including an extended admin interface, web (un)subscription, dynamic e-mail templates, an archive and HTML email support.
Python
825
star
36

django-avatar

A Django app for handling user avatars.
Python
797
star
37

django-formtools

A set of high-level abstractions for Django forms
Python
735
star
38

django-user-sessions

Extend Django sessions with a foreign key back to the user, allowing enumerating all user's sessions.
Python
586
star
39

django-admin-sortable

Generic drag-and-drop ordering for objects and tabular inlines in Django Admin
Python
557
star
40

django-invitations

Generic invitations app for Django
Python
530
star
41

django-sortedm2m

A transparent sorted ManyToMany field for django.
Python
508
star
42

django-recurrence

Utility for working with recurring dates in Django.
Python
460
star
43

django-categories

This app attempts to provide a generic category system that multiple apps could use. It uses MPTT for the tree storage and provides a custom admin for better visualization (copied and modified from feinCMS).
Python
455
star
44

django-robots

A Django app for managing robots.txt files following the robots exclusion protocol
Python
451
star
45

django-embed-video

Django app for easy embedding YouTube and Vimeo videos and music from SoundCloud.
Python
383
star
46

wagtailmenus

An app to help you manage and render menus in your Wagtail projects more effectively
Python
380
star
47

django-downloadview

Serve files with Django.
Python
357
star
48

jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
Python
328
star
49

django-queued-storage

Provides a proxy for Django storage backends that allows you to upload files locally and eventually serve them remotely
Python
314
star
50

django-permission

[Not maintained] An enhanced permission system which support object permission in Django
Python
302
star
51

django-eav2

Django EAV 2 - EAV storage for modern Django
Python
297
star
52

django-revproxy

Reverse Proxy view that supports all HTTP methods, Diazo transformations and Single Sign-On.
Python
290
star
53

django-authority

A Django app that provides generic per-object-permissions for Django's auth app and helpers to create custom permission checks.
Python
286
star
54

django-simple-menu

Simple, yet powerful, code-based menus for Django applications
Python
258
star
55

django-dbtemplates

Django template loader for database stored templates with extensible cache backend
JavaScript
250
star
56

django-mongonaut

Built from scratch to replicate some of the Django admin functionality and add some more, to serve as an introspective interface for Django and Mongo.
Python
240
star
57

django-fsm-log

Automatic logging for Django FSM
Python
235
star
58

django-cookie-consent

Reusable application for managing various cookies and visitors consent for their use in Django project.
Python
210
star
59

django-celery-monitor

Celery Monitoring for Django
Python
191
star
60

django-ddp

Django/PostgreSQL implementation of the Meteor server.
Python
167
star
61

icalevents

Python module for iCal URL/file parsing and querying.
Python
153
star
62

docopt-ng

Humane command line arguments parser. Now with maintenance, typehints, and complete test coverage.
Python
149
star
63

django-voting

A generic voting application for Django
Python
93
star
64

django-ical

iCal feeds for Django based on Django's syndication feed framework.
Python
89
star
65

django-flatblocks

django-chunks + headerfield + variable chunknames + "inclusion tag" == django-flatblocks
Python
82
star
66

django-redshift-backend

Redshift database backend for Django
Python
80
star
67

pathlib2

Backport of pathlib aiming to support the full stdlib Python API.
Python
80
star
68

website

Code for the Jazzband website
Python
63
star
69

django-sorter

A helper app for sorting objects in Django templates.
Python
53
star
70

django-discover-jenkins

A streamlined fork of django-jenkins designed to work with the default test command and the discover runner
Python
49
star
71

contextlib2

contextlib2 is a backport of the standard library's contextlib module to earlier Python versions.
Python
37
star
72

django-fernet-encrypted-fields

Python
35
star
73

imaplib2

Fork of Piers Lauder's imaplib2 library for Python.
Python
31
star
74

help

Use this repo to get help from the roadies
27
star
75

.github

Community health and config files for Jazzband
7
star
76

django-postgres-utils

Django app providing additional lookups and functions for PostgreSQL
Python
7
star
77

admin

Some admin files for Jazzband
3
star
78

actions

Various GitHub actions for Jazzband projects
1
star