geojson

repository·main·Indexed 21 days ago

https://github.com/jazzband/geojson

A Python library for encoding and decoding GeoJSON formatted data. It provides classes for standard GeoJSON objects, implements the __geo_interface__ specification, and includes utilities for coordinate manipulation, validation, and random data generation. Compatible with Python 3.10 through 3.14.

Tokens
2.9K
Snippets
16
Records
16
Agent score
27%

What's inside geojson

  1. Manage coordinate precision

    main

    GeoJSON objects in this library round coordinates to a specific number of decimal places.

    • Per-instance precision: Pass a precision argument when instantiating an object.
    • Package-level precision: Set geojson.geometry.DEFAULT_PRECISION to change the default rounding for the entire package.

    Note: Setting DEFAULT_PRECISION also affects the rounding behavior when using geojson.load or geojson.loads. A common pattern to scale down precision for large datasets is to perform a load/loads followed by a dump/dumps.

    from geojson import Point
    import geojson
    
    # Per-instance precision
    point = Point((-115.12341234, 37.12341234), precision=8)
    
    # Package-level precision
    geojson.geometry.DEFAULT_PRECISION = 5
    point_default = Point((-115.12341234, 37.12341234))
  2. Extend GeoJSON encoding to custom classes

    main

    You can make your own Python classes compatible with geojson.dumps and geojson.loads by implementing the __geo_interface__ property. This property should return a dictionary representing the GeoJSON structure (e.g., containing type and coordinates).

    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)
    print(geojson.dumps(point_instance, sort_keys=True))
  3. Create GeoJSON Feature objects

    main

    Use the Feature class to create a GeoJSON Feature. A Feature combines a geometry with properties (a dictionary) and an optional id.

    from geojson import Feature, Point
    
    my_point = Point((-3.68, 40.41))
    
    # Basic feature
    feat = Feature(geometry=my_point)
    
    # Feature with properties
    feat_with_props = Feature(geometry=my_point, properties={"country": "Spain"})
    
    # Feature with an ID
    feat_with_id = Feature(geometry=my_point, id=27)
  4. Create GeoJSON MultiLineString objects

    main

    Use the MultiLineString class to create a GeoJSON MultiLineString object by passing a list of lists of coordinate tuples.

    from geojson import MultiLineString
    
    multi_line = MultiLineString([
        [(3.75, 9.25), (-130.95, 1.52)],
        [(23.15, -34.25), (-1.35, -4.65), (3.45, 77.95)]
    ])
    # Result: {'coordinates': [[[3.75, 9.25], [-130.95, 1.52]], [[23.15, -34.25], [-1.35, -4.65], [3.45, 77.95]]], 'type': 'MultiLineString'}
  5. Create GeoJSON Polygon objects

    main

    Use the Polygon class to create a GeoJSON Polygon object. The coordinates should be a list of rings, where the first ring is the exterior boundary and subsequent rings are holes.

    from geojson import Polygon
    
    # Polygon with no holes
    poly_no_holes = Polygon([[(2.38, 57.322), (-120.43, 19.15), (23.194, -20.28), (2.38, 57.322)]])
    
    # Polygon with a hole
    poly_with_hole = 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)]
    ])
  6. Validate GeoJSON objects

    main

    Use the .is_valid property to check if a GeoJSON object adheres to the specification. If validation fails, use the .errors() method to retrieve a description of the validation errors.

    import geojson
    
    obj = geojson.Point((-3.68, 40.41, 25.14, 10.34))
    if not obj.is_valid:
        print(obj.errors())  # e.g., 'a position must have exactly 2 or 3 values'
  7. Generate random GeoJSON data

    main

    Use geojson.utils.generate_random(type_name) to create a geometry object of a specified type (e.g., "LineString", "Polygon") populated with random coordinate data.

    import geojson
    
    random_line = geojson.utils.generate_random("LineString")
    random_polygon = geojson.utils.generate_random("Polygon")
  8. Encode and decode GeoJSON objects

    main

    Use geojson.dump, geojson.dumps, geojson.load, and geojson.loads to convert GeoJSON objects to and from raw JSON. These functions are wrappers around the standard Python json module and accept any additional arguments supported by the core json functions (e.g., sort_keys=True), allowing you to control formatting and parsing behavior.

    import geojson
    
    my_point = geojson.Point((43.24, -1.532))
    dump = geojson.dumps(my_point, sort_keys=True)
    new_point = geojson.loads(dump)
  9. Create GeoJSON FeatureCollection objects

    main

    Use the FeatureCollection class to group multiple Feature objects. You can index a FeatureCollection directly to access its features, and use the .errors() method to check for validation issues.

    from geojson import Feature, Point, FeatureCollection
    
    feat1 = Feature(geometry=Point((1.6432, -19.123)))
    feat2 = Feature(geometry=Point((-80.234, -22.532)))
    
    fc = FeatureCollection([feat1, feat2])
    
    # Accessing features
    first_feature = fc[0]
    
    # Checking for errors
    errors = fc.errors()
  10. Create GeoJSON LineString objects

    main

    Use the LineString class to create a GeoJSON LineString object by passing a list of coordinate tuples representing the path.

    from geojson import LineString
    
    line = LineString([(8.919, 44.4074), (8.923, 44.4075)])
    # Result: {'coordinates': [[8.919, 44.4074], [8.923, 44.4075]], 'type': 'LineString'}
  11. Create GeoJSON MultiPoint objects

    main

    Use the MultiPoint class to create a GeoJSON MultiPoint object by passing a list of coordinate tuples.

    from geojson import MultiPoint
    
    multi_point = MultiPoint([(-155.52, 19.61), (-156.22, 20.74), (-157.97, 21.46)])
    # Result: {'coordinates': [[-155.52, 19.61], [-156.22, 20.74], [-157.97, 21.46]], 'type': 'MultiPoint'}