### Install geojson Python Package Source: https://github.com/jazzband/geojson/blob/main/README.rst Install the geojson library using pip. This is the recommended installation method. ```bash pip install geojson ``` -------------------------------- ### Python GeoJSON dump() and dumps() examples Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Demonstrates creating a Point object and serializing it to a compact JSON string, a pretty-printed JSON string, and writing to a file using geojson.dumps() and geojson.dump(). ```python import geojson point = geojson.Point((-115.81, 37.24)) # Compact output json_str = geojson.dumps(point) # Pretty-printed output json_str = geojson.dumps(point, indent=2, sort_keys=True) # Write to file with open('output.json', 'w') as f: geojson.dump(point, f, indent=2) ``` -------------------------------- ### Python GeoJSON load() and loads() examples Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Demonstrates deserializing a GeoJSON Point from a string using geojson.loads() and loading GeoJSON data from a file using geojson.load(). Shows the resulting object type. ```python import geojson # Load with custom object hook (already default) json_str = '{"type": "Point", "coordinates": [0, 0]}' point = geojson.loads(json_str) print(type(point)) # # Load from file with open('data.json', 'r') as f: data = geojson.load(f) ``` -------------------------------- ### Buffer Geometries (Simple) Source: https://github.com/jazzband/geojson/blob/main/_autodocs/README.md Perform simple geometric buffering by applying a scaling factor to coordinates using `utils.map_coords`. This example expands a bounding box by 10%. ```python from geojson import utils # Expand bounding box by 10% buffered = utils.map_coords(lambda x: x * 1.1, geometry) ``` -------------------------------- ### Implement __geo_interface__ protocol for custom objects Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/mapping.md Shows an example implementation of the __geo_interface__ protocol for a custom class, enabling it to be serialized as GeoJSON using the geojson library. This promotes interoperability. ```python from geojson import dumps class Location: def __init__(self, name, lon, lat): self.name = name self.lon = lon self.lat = lat @property def __geo_interface__(self): return { "type": "Feature", "geometry": { "type": "Point", "coordinates": [self.lon, self.lat] }, "properties": { "name": self.name } } # Use with geojson location = Location("New York", -74.0, 40.7) json_str = dumps(location) print(json_str) # {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-74.0, 40.7]}, "properties": {"name": "New York"}} ``` -------------------------------- ### Geometry Transform Function Example Source: https://github.com/jazzband/geojson/blob/main/_autodocs/types.md Shows how to apply a coordinate transformation to geometries within a `GeometryCollection` using `map_geometries` and `map_coords`. ```python import geojson collection = geojson.GeometryCollection([ geojson.Point((10, 20)) ]) result = geojson.utils.map_geometries( lambda g: geojson.utils.map_coords(lambda x: x * 2, g), collection ) ``` -------------------------------- ### Get Package Version String Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md Access the current version of the geojson library as a string. ```python __version__: str = "3.3.0" ``` -------------------------------- ### Coordinate Transform Function Example Source: https://github.com/jazzband/geojson/blob/main/_autodocs/types.md Demonstrates using `map_coords` for scalar transformation and `map_tuples` for swapping coordinate values within a GeoJSON Point object. ```python import geojson point = geojson.Point((90, 45)) # Simple scalar transformation scaled = geojson.utils.map_coords(lambda x: x * 0.5, point) # Tuple transformation swapped = geojson.utils.map_tuples(lambda c: (c[1], c[0]), point) ``` -------------------------------- ### Coordinate Precision Example Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Illustrates how to set coordinate precision for individual Point objects, overriding the global default. The 'precision' parameter rounds coordinates to the specified number of decimal places. ```python from geojson import Point import geojson # Global default geojson.geometry.DEFAULT_PRECISION = 6 # Per-object override point1 = Point((-115.123456789, 37.123456789)) # Uses 6 (global) print(point1) # {"coordinates": [-115.123457, 37.123457], "type": "Point"} point2 = Point((-115.123456789, 37.123456789), precision=3) # Uses 3 print(point2) # {"coordinates": [-115.123, 37.123], "type": "Point"} ``` -------------------------------- ### Point Validation Example Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Demonstrates how the 'validate' parameter affects Point construction. When 'validate=True', invalid coordinates raise a ValueError. Without validation, invalidity is only detected via '.is_valid'. ```python from geojson import Point # Without validation (default) invalid = Point((-115.81, 37.24, 100, 200)) print(invalid.is_valid) # False (but no exception) # With validation (raises exception) try: invalid = Point((-115.81, 37.24, 100, 200), validate=True) except ValueError as e: print(f"Construction failed: {e}") # "a position must have exactly 2 or 3 values: [...]" ``` -------------------------------- ### Geometry Type Identification Example Source: https://github.com/jazzband/geojson/blob/main/_autodocs/types.md Shows how to access the 'type' field of GeoJSON objects like Point and Feature to retrieve their geometry type string. ```python from geojson import Point, Feature point = Point((0, 0)) print(point['type']) # "Point" feature = Feature(geometry=point) print(feature['type']) # "Feature" ``` -------------------------------- ### Custom GeoJSON Object Creation Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/factory.md Provides examples of extending GeoJSON functionality by creating custom wrapper classes that inherit from existing GeoJSON classes or by using composition with the `__geo_interface__` property. ```python import geojson # Create custom wrapper class MyPoint(geojson.Point): def custom_method(self): return "Custom point" point = MyPoint((-115.81, 37.24)) print(point.custom_method()) # "Custom point" # Or use composition with __geo_interface__ class CustomGeometry: def __init__(self, geometry): self.geometry = geometry @property def __geo_interface__(self): return dict(self.geometry) original = geojson.Point((-115.81, 37.24)) custom = CustomGeometry(original) print(geojson.dumps(custom)) ``` -------------------------------- ### Point Creation with Precision Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Demonstrates creating Point objects with default and custom precision settings. Validation can be enabled to catch errors in coordinate data. ```python from geojson import Point, LineString # Basic point with default precision (6 decimal places) point = Point((-115.123412341234, 37.123412341234)) # Result: {"coordinates": [-115.123412, 37.123412], "type": "Point"} # Point with custom precision (8 decimal places) point = Point((-115.123412341234, 37.123412341234), precision=8) # Result: {"coordinates": [-115.12341234, 37.12341234], "type": "Point"} # Validate coordinates during construction try: invalid = Point((-115.123412341234, 37.123412341234, 25.14, 10.34), validate=True) except ValueError as e: print(f"Validation failed: {e}") ``` -------------------------------- ### Create 2D and 3D Point Objects Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Demonstrates how to instantiate Point objects for both two-dimensional (longitude, latitude) and three-dimensional (longitude, latitude, elevation) geographic coordinates. ```python from geojson import Point # 2D point (longitude, latitude) point_2d = Point((-115.81, 37.24)) print(point_2d) # {"coordinates": [-115.81, 37.24], "type": "Point"} # 3D point (longitude, latitude, elevation) point_3d = Point((-115.81, 37.24, 1000)) print(point_3d) # {"coordinates": [-115.81, 37.24, 1000], "type": "Point"} ``` -------------------------------- ### Get Package Version Tuple Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md Access the current version of the geojson library as a tuple of integers. ```python __version_info__: tuple = (3, 3, 0) ``` -------------------------------- ### Get Coordinate Tuples from Geometry Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md Use this generator to yield all coordinate tuples from a geometry or feature object. ```python def coords(obj) -> generator ``` -------------------------------- ### Create a GeometryCollection Source: https://github.com/jazzband/geojson/blob/main/README.rst Demonstrates creating a GeometryCollection by combining Point and LineString objects. Access individual geometries using indexing. ```python >>> 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 ``` -------------------------------- ### Get GeoJSON Validation Errors Source: https://github.com/jazzband/geojson/blob/main/README.rst Retrieves a collection of errors for an invalid GeoJSON object using the `errors` method. ```python >>> import geojson >>> obj = geojson.Point((-3.68,40.41,25.14,10.34)) >>> obj.errors() 'a position must have exactly 2 or 3 values' ``` -------------------------------- ### Feature Constructor with Geometry Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Shows how to initialize a Feature with a Geometry object or a dictionary representation of geometry. Also demonstrates creating a feature with null geometry. ```python from geojson import Feature, Point # With Geometry object point = Point((0, 0)) feature = Feature(geometry=point) # With dictionary geom_dict = {"type": "Point", "coordinates": [0, 0]} feature = Feature(geometry=geom_dict) # With None (null geometry) feature = Feature(geometry=None, properties={"name": "Null geometry"}) ``` -------------------------------- ### Set Instance Coordinate Precision Source: https://github.com/jazzband/geojson/blob/main/README.rst Demonstrates how to create a Point object with default precision and then with a specified precision. ```python >>> from geojson import Point >>> Point((-115.123412341234, 37.1234123412341234)) # 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"} ``` -------------------------------- ### Feature Creation with Properties Source: https://github.com/jazzband/geojson/blob/main/_autodocs/types.md Demonstrates creating a Feature object with associated properties, including various data types like strings, integers, and booleans. ```python from geojson import Feature, Point feature = Feature( geometry=Point((0, 0)), properties={ "name": "Test Location", "elevation": 1000, "visited": True } ) print(feature.properties['name']) # "Test Location" ``` -------------------------------- ### Module Entry Point Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md All items listed below are available from the main `geojson` module. ```APIDOC ## Module Entry Point **Import Location:** `geojson` All items listed below are available from the main `geojson` module: ```python from geojson import Point, Feature, dump, dumps, load, loads, coords, map_coords, __version__ ``` ``` -------------------------------- ### Feature Constructor with ID Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Demonstrates creating Feature objects with integer and string IDs, and shows how to check for the presence and value of the ID. ```python from geojson import Feature, Point # With integer ID f1 = Feature(id=1, geometry=Point((0, 0))) print('id' in f1) # True print(f1['id']) # 1 # With string ID f2 = Feature(id="location-001", geometry=Point((1, 1))) print(f2['id']) # "location-001" # Without ID f3 = Feature(geometry=Point((2, 2))) print('id' in f3) # False ``` -------------------------------- ### Recommended Complete Import Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md A curated import statement including common geometries, features, utilities, and the version. This is the recommended way to import for most use cases. ```python from geojson import ( # Geometries Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection, # Features Feature, FeatureCollection, # Utilities dump, dumps, load, loads, coords, map_coords, # Version __version__ ) ``` -------------------------------- ### Constructor Options Source: https://github.com/jazzband/geojson/blob/main/_autodocs/COMPLETION_SUMMARY.txt Details on the configuration options available when constructing geojson objects. ```APIDOC ## Constructor Options ### Geometry Options - `coordinates`: Position or geometry data. - `validate`: Boolean flag to enable/disable validation. - `precision`: Integer specifying decimal places for coordinates. ### Feature Options - `id`: Identifier for the Feature. - `geometry`: GeoJSON geometry object. - `properties`: Dictionary for Feature properties. ### FeatureCollection Options - `features`: An array of Feature objects. ### Codec Options - Description: All available JSON serialization parameters. ``` -------------------------------- ### Feature Constructor with Properties Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Illustrates creating a Feature with associated properties, including various JSON-serializable data types. Accessing properties is also shown. ```python from geojson import Feature, Point feature = Feature( geometry=Point((0, 0)), properties={ "name": "Location A", "population": 10000, "active": True, "tags": ["city", "major"] } ) print(feature.properties['name']) # "Location A" print(feature['properties']['population']) # 10000 ``` -------------------------------- ### Create and Print FeatureCollection Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/feature.md Demonstrates how to create a FeatureCollection from individual Feature objects and print its JSON representation. Also shows index access and validation. ```python from geojson import Feature, Point, FeatureCollection # Create individual features feature_1 = Feature(geometry=Point((1.6432, -19.123))) feature_2 = Feature(geometry=Point((-80.234, -22.532))) # Create feature collection collection = FeatureCollection([feature_1, feature_2]) print(collection) # {"features": [{"geometry": {"coordinates": [1.6432, -19.123], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-80.234, -22.532], "type": "Point"}, "properties": {}, "type": "Feature"}], "type": "FeatureCollection"} # Index access print(collection[0] == collection['features'][0]) # True print(collection[1] == feature_2) # True # Validate collection print(collection.errors()) # [] (no errors) print(collection.is_valid) # True ``` -------------------------------- ### Create a Feature Source: https://github.com/jazzband/geojson/blob/main/README.rst Shows how to create a Feature with a geometry, properties, and an optional ID. Features can be created with just geometry, or with additional properties and an identifier. ```python >>> 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"} ``` -------------------------------- ### Point Geometry Creation Source: https://github.com/jazzband/geojson/blob/main/_autodocs/types.md Demonstrates creating Point objects with both 2D and 3D coordinates using the Point class. ```python from geojson import Point # 2D point_2d = Point((10.5, 20.3)) # 3D point_3d = Point((10.5, 20.3, 1000)) ``` -------------------------------- ### Import All Utility Functions Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md Imports all available utility functions for data manipulation and conversion. Includes functions for loading, dumping, and coordinate mapping. ```python from geojson import ( dump, dumps, load, loads, coords, map_coords ) ``` -------------------------------- ### Global Settings Source: https://github.com/jazzband/geojson/blob/main/_autodocs/COMPLETION_SUMMARY.txt Information on global configuration settings and their precedence. ```APIDOC ## Global Settings ### `DEFAULT_PRECISION` - Description: Sets the default coordinate precision globally. ### Modification Methods - Description: Details on how to modify global settings. ### Precedence Rules - Description: Explains how per-object settings override global settings. ``` -------------------------------- ### Create a FeatureCollection Source: https://github.com/jazzband/geojson/blob/main/README.rst Demonstrates creating a FeatureCollection by combining multiple Feature objects. You can access individual features by index and check for errors in the collection. ```python >>> 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) ``` -------------------------------- ### Feature Creation with IDs Source: https://github.com/jazzband/geojson/blob/main/_autodocs/types.md Demonstrates creating Feature objects with integer, string, and no IDs. The 'id' field is optional and only present if explicitly set. ```python from geojson import Feature, Point # Integer ID feature_1 = Feature(id=1, geometry=Point((0, 0))) print(feature_1['id']) # 1 # String ID feature_2 = Feature(id="location-001", geometry=Point((1, 1))) print(feature_2['id']) # "location-001" # No ID feature_3 = Feature(geometry=Point((2, 2))) print('id' in feature_3) # False ``` -------------------------------- ### Create GeometryCollection with default geometries Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Instantiate a GeometryCollection without providing any geometries. This results in an empty GeometryCollection. ```python from geojson import GeometryCollection gc = GeometryCollection() print(gc.geometries) # [] ``` -------------------------------- ### Create a Point object Source: https://github.com/jazzband/geojson/blob/main/docs/source/index.md Create a Point object with longitude and latitude coordinates. The output shows the JSON representation of the Point. ```python >>> from geojson import Point >>> Point((-115.81, 37.24)) {"coordinates": [-115.8..., 37.2...], "type": "Point"} ``` -------------------------------- ### Create and Validate LineString Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Instantiate a LineString object with multiple points and check its validity. The constructor requires at least two points. ```Python # More complex line path = LineString([ (-152.62, 51.21), (5.21, 10.69), (12.34, 56.78) ]) print(path.is_valid) # True ``` -------------------------------- ### Create FeatureCollection with Feature objects Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Instantiate a FeatureCollection using a list of Feature objects. Ensure Feature objects are properly created before passing them. ```python from geojson import FeatureCollection, Feature, Point # With Feature objects f1 = Feature(geometry=Point((0, 0))) f2 = Feature(geometry=Point((1, 1))) fc = FeatureCollection([f1, f2]) ``` -------------------------------- ### Dynamic Class Lookup and Instantiation Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/factory.md Shows how to dynamically retrieve GeoJSON classes from the factory using `getattr()` based on their type string and then instantiate them. This is useful when the type of GeoJSON object is determined at runtime. ```python import geojson import geojson.factory # Get class by type string PointClass = getattr(geojson.factory, "Point") LineStringClass = getattr(geojson.factory, "LineString") # Instantiate dynamically point = PointClass(coordinates=[10, 20]) line = LineStringClass(coordinates=[[0, 0], [1, 1]]) ``` -------------------------------- ### Create and Print LineString Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Instantiate a LineString object with a list of coordinate tuples and print its GeoJSON representation. Requires at least two points. ```Python from geojson import LineString # Simple line with 2 points line = LineString([(8.919, 44.4074), (8.923, 44.4075)]) print(line) # {"coordinates": [[8.919, 44.4074], [8.923, 44.4075]], "type": "LineString"} ``` -------------------------------- ### Access Point Coordinates Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Shows how to retrieve the coordinate data from a Point object, both as a dictionary key and as an attribute. ```python # Access as dictionary print(point_2d['coordinates']) # [-115.81, 37.24] print(point_2d.coordinates) # [-115.81, 37.24] (attribute access) ``` -------------------------------- ### Configure GeoJSON Precision and Create Objects Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Set global precision for all subsequent GeoJSON objects or specify precision per object. Demonstrates creating Point objects with default and custom precision, and a Feature object with properties. ```python import geojson # Set global precision to 4 decimal places geojso n.geometry.DEFAULT_PRECISION = 4 # Create point with default global precision point1 = geojson.Point((-115.123456789, 37.123456789)) print(geojson.dumps(point1)) # {"coordinates": [-115.1235, 37.1235], "type": "Point"} # Create point with custom precision point2 = geojson.Point((-115.123456789, 37.123456789), precision=8) print(geojson.dumps(point2)) # {"coordinates": [-115.12345679, 37.12345679], "type": "Point"} # Create feature with custom properties feature = geojson.Feature( id="location-1", geometry=point1, properties={"name": "Test", "temperature": 25.5}, source="GPS" ) ``` -------------------------------- ### Import Version Information Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md Imports the library's version number and version info tuple. Useful for checking compatibility or logging. ```python from geojson import __version__, __version_info__ ``` -------------------------------- ### Feature Constructor with Extra Arguments Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Demonstrates how to include additional, non-standard fields in a Feature object using arbitrary keyword arguments. These fields are directly added to the feature. ```python from geojson import Feature, Point feature = Feature( geometry=Point((0, 0)), properties={"name": "Test"}, custom_field="custom_value", metadata={"source": "import"} ) print(feature['custom_field']) # "custom_value" ``` -------------------------------- ### Create GeometryCollection with geometry objects Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Instantiate a GeometryCollection using a list of geometry objects. The collection can hold various geometry types like Point and LineString. ```python from geojson import GeometryCollection, Point, LineString point = Point((23.532, -63.12)) line = LineString([(-152.62, 51.21), (5.21, 10.69)]) gc = GeometryCollection([point, line]) # Access geometries print(gc[0]) # Point print(gc[1]) # LineString print(gc.geometries[0] == gc[0]) # True ``` -------------------------------- ### Create a FeatureCollection Source: https://github.com/jazzband/geojson/blob/main/docs/source/index.md Build a FeatureCollection by passing a list of Feature objects. You can check for errors and access individual features using indexing. ```python >>> 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 {"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) ``` -------------------------------- ### Create and Print MultiPoint Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Instantiate a MultiPoint object with a list of coordinate tuples and print its GeoJSON representation. ```Python from geojson import MultiPoint points = MultiPoint([ (-155.52, 19.61), (-156.22, 20.74), (-157.97, 21.46) ]) print(points) # {"coordinates": [[-155.52, 19.61], [-156.22, 20.74], [-157.97, 21.46]], "type": "MultiPoint"} ``` -------------------------------- ### Feature Constructor Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/feature.md Initializes a Feature object with an optional ID, geometry, properties, and additional key-value pairs. ```APIDOC ## Feature Constructor ### Description Initializes a Feature object with an optional ID, geometry, properties, and additional key-value pairs. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (str or int) - Optional - Unique identifier for the feature (added to output only if provided) - **geometry** (Geometry or dict) - Optional - Geometry object representing the feature's spatial extent (Point, LineString, Polygon, etc.) - **properties** (dict) - Optional - Dictionary of properties/attributes associated with the feature - **extra** (kwargs) - Optional - Additional key-value pairs added to the Feature object ### Request Example ```python from geojson import Feature, Point # Feature with geometry only my_point = Point((-3.68, 40.41)) feature = Feature(geometry=my_point) print(feature) # Feature with properties feature = Feature( geometry=my_point, properties={"country": "Spain", "city": "Madrid"} ) print(feature) # Feature with ID feature = Feature( id=27, geometry=my_point, properties={"name": "Location"} ) print(feature) ``` ### Response #### Success Response (200) Feature instance #### Response Example ```json { "geometry": {"coordinates": [-3.68, 40.41], "type": "Point"}, "properties": {}, "type": "Feature" } ``` ``` -------------------------------- ### __version__ Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md The current version string of the geojson library. ```APIDOC ## __version__ ### Description Current version string. ### Type ```python str ``` ### Value ``` "3.3.0" ``` ``` -------------------------------- ### Create a Feature with Geometry Source: https://github.com/jazzband/geojson/blob/main/docs/source/index.md Instantiate a Feature object by assigning a geometry and optionally providing properties and an ID. The properties are stored in a dictionary. ```python >>> from geojson import Feature, Point >>> my_point = Point((-3.68, 40.41)) >>> Feature(geometry=my_point) {"geometry": {"coordinates": [-3.68..., 40.4...], "type": "Point"}, "properties": {}, "type": "Feature"} >>> Feature(geometry=my_point, properties={"country": "Spain"}) {"geometry": {"coordinates": [-3.68..., 40.4...], "type": "Point"}, "properties": {"country": "Spain"}, "type": "Feature"} >>> Feature(geometry=my_point, id=27) {"geometry": {"coordinates": [-3.68..., 40.4...], "type": "Point"}, "id": 27, "properties": {}, "type": "Feature"} ``` -------------------------------- ### MultiLineString Constructor Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Represents multiple line strings as a collection. Accepts a list of LineString coordinate arrays. ```APIDOC ## MultiLineString Represents multiple line strings as a collection. ### Constructor ```python class MultiLineString(Geometry): def __init__(self, coordinates=None, validate=False, precision=None, **extra) ``` #### Parameters - **coordinates** (list) - Optional - List of LineString coordinate arrays, each with minimum 2 points. Defaults to `[]`. - **validate** (bool) - Optional - If `True`, raises `ValueError` for invalid line strings. Defaults to `False`. - **precision** (int) - Optional - Decimal places for coordinate rounding. Defaults to `DEFAULT_PRECISION` (6). - **extra** (kwargs) - Optional - Additional GeoJSON properties. **Returns:** MultiLineString instance **Example:** ```python from geojson import MultiLineString lines = MultiLineString([ [(3.75, 9.25), (-130.95, 1.52)], [(23.15, -34.25), (-1.35, -4.65), (3.45, 77.95)] ]) print(lines) # {"coordinates": [[[3.75, 9.25], [-130.95, 1.52]], [[23.15, -34.25], [-1.35, -4.65], [3.45, 77.95]]], "type": "MultiLineString"} ``` ### Methods #### errors ```python def errors() -> list ``` **Returns:** List of error messages from invalid line strings; empty list if all valid ``` -------------------------------- ### Create a GeometryCollection object Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Construct a GeometryCollection by providing a list of existing geometry objects. Supports index access to individual geometries within the collection. ```python from geojson import GeometryCollection, Point, LineString my_point = Point((23.532, -63.12)) my_line = LineString([(-152.62, 51.21), (5.21, 10.69)]) collection = GeometryCollection([my_point, my_line]) print(collection) # {"geometries": [{"coordinates": [23.532, -63.12], "type": "Point"}, {"coordinates": [[-152.62, 51.21], [5.21, 10.69]], "type": "LineString"}], "type": "GeometryCollection"} # Index access to geometries print(collection[0]) # Point print(collection[1]) # LineString print(collection.geometries[0] == collection[0]) # True ``` -------------------------------- ### Geometry Constructor Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Initializes a Geometry object with coordinate data, validation options, and precision control. Accepts additional keyword arguments for custom properties. ```APIDOC ## Geometry Constructor ### Description Initializes a Geometry object with coordinate data, validation options, and precision control. Accepts additional keyword arguments for custom properties. ### Signature ```python class Geometry(GeoJSON): def __init__(self, coordinates=None, validate=False, precision=None, **extra) ``` ### Parameters #### Parameters - **coordinates** (tuple or list) - Optional - `[]` - Coordinate data for the geometry, can be nested tuples/lists or Geometry instances - **validate** (bool) - Optional - `False` - If `True`, raises `ValueError` if validation errors are present in coordinates - **precision** (int) - Optional - `DEFAULT_PRECISION` (6) - Number of decimal places to round latitude/longitude coordinates to - **extra** (kwargs) - Optional - — - Additional key-value pairs added to the GeoJSON object ### Returns Geometry instance (dict-like object) ### Example ```python from geojson import Point, LineString # Basic point with default precision (6 decimal places) point = Point((-115.123412341234, 37.123412341234)) # Result: {"coordinates": [-115.123412, 37.123412], "type": "Point"} # Point with custom precision (8 decimal places) point = Point((-115.123412341234, 37.123412341234), precision=8) # Result: {"coordinates": [-115.12341234, 37.12341234], "type": "Point"} # Validate coordinates during construction try: invalid = Point((-115.123412341234, 37.123412341234, 25.14, 10.34), validate=True) except ValueError as e: print(f"Validation failed: {e}") ``` ``` -------------------------------- ### Create GeoJSON Geometries in Python Source: https://github.com/jazzband/geojson/blob/main/_autodocs/README.md Use classes like Point, LineString, Feature, and FeatureCollection to construct GeoJSON objects. Import necessary classes from the geojson library. ```python from geojson import Point, LineString, Feature, FeatureCollection # Simple point point = Point((-115.81, 37.24)) # Line with multiple points line = LineString([(-152.62, 51.21), (5.21, 10.69)]) # Feature with properties feature = Feature( geometry=point, properties={"name": "Test", "elevation": 1000} ) # Collection collection = FeatureCollection([feature]) ``` -------------------------------- ### Create a GeoJSON Point Object Source: https://github.com/jazzband/geojson/blob/main/README.rst Instantiate a Point object with longitude and latitude coordinates. The object can be used to represent a single geographical location. ```python >>> from geojson import Point >>> Point((-115.81, 37.24)) # doctest: +ELLIPSIS {"coordinates": [-115.8..., 37.2...], "type": "Point"} ``` -------------------------------- ### Import All Geometry and Feature Classes Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md Imports all available geometry and feature classes from the geojson library. Useful for comprehensive usage. ```python from geojson import ( Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature, FeatureCollection, GeoJSON ) ``` -------------------------------- ### Point Constructor with 3D Coordinates Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Constructs a 3D Point object including altitude. ```python # 3D point = Point((-115.81, 37.24, 1000)) ``` -------------------------------- ### FeatureCollection Constructor Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/feature.md Initializes a FeatureCollection object with a list of features and optional extra keyword arguments. ```APIDOC ## FeatureCollection Constructor ### Description Initializes a FeatureCollection object with a list of features and optional extra keyword arguments. ### Method __init__ ### Parameters #### Path Parameters - **features** (list) - Required - List of Feature objects or dicts convertible to Feature objects - **extra** (kwargs) - Optional - Additional key-value pairs added to the FeatureCollection object ### Request Example ```python from geojson import Feature, Point, FeatureCollection feature_1 = Feature(geometry=Point((1.6432, -19.123))) feature_2 = Feature(geometry=Point((-80.234, -22.532))) collection = FeatureCollection([feature_1, feature_2]) print(collection) ``` ### Response #### Success Response - **FeatureCollection instance** #### Response Example ```json { "features": [ { "geometry": { "coordinates": [ 1.6432, -19.123 ], "type": "Point" }, "properties": {}, "type": "Feature" }, { "geometry": { "coordinates": [ -80.234, -22.532 ], "type": "Point" }, "properties": {}, "type": "Feature" } ], "type": "FeatureCollection" } ``` ``` -------------------------------- ### Dump and Load GeoJSON with Formatting and Precision Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Serialize a GeoJSON Feature object to a file with indentation and sorted keys. Then, load the GeoJSON back from the file after resetting the global precision. ```python # Dump with formatting with open('output.json', 'w') as f: geojson.dump(feature, f, indent=2, sort_keys=True) # Load back with custom precision geojso n.geometry.DEFAULT_PRECISION = 2 with open('output.json', 'r') as f: loaded = geojson.load(f) ``` -------------------------------- ### Point Constructor with 2D Coordinates Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Constructs a 2D Point object using a tuple of longitude and latitude. ```python from geojson import Point # 2D point = Point((-115.81, 37.24)) ``` -------------------------------- ### Point Constructor from Another Point Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Creates a new Point object by extracting coordinates from an existing Point instance. ```python # From another Point other = Point((-115.81, 37.24)) point = Point(other) # Extracts coordinates ``` -------------------------------- ### Geometry Constructor Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Initializes a Geometry object. Supports default or custom precision for coordinates and optional validation. ```python class Geometry(GeoJSON): def __init__(self, coordinates=None, validate=False, precision=None, **extra) ``` -------------------------------- ### Create a GeoJSON Feature Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/feature.md Instantiate a Feature object with geometry, properties, and an optional ID. The constructor accepts geometry and properties as arguments, and any additional keyword arguments are stored as extra properties. ```python from geojson import Feature, Point # Feature with geometry only my_point = Point((-3.68, 40.41)) feature = Feature(geometry=my_point) print(feature) # {"geometry": {"coordinates": [-3.68, 40.41], "type": "Point"}, "properties": {}, "type": "Feature"} ``` ```python from geojson import Feature, Point # Feature with properties feature = Feature( geometry=my_point, properties={"country": "Spain", "city": "Madrid"} ) print(feature) # {"geometry": {"coordinates": [-3.68, 40.41], "type": "Point"}, "properties": {"country": "Spain", "city": "Madrid"}, "type": "Feature"} ``` ```python from geojson import Feature, Point # Feature with ID feature = Feature( id=27, geometry=my_point, properties={"name": "Location"} ) print(feature) # {"id": 27, "geometry": {"coordinates": [-3.68, 40.41], "type": "Point"}, "properties": {"name": "Location"}, "type": "Feature"} ``` -------------------------------- ### Generate Random Point with Bounding Box Source: https://github.com/jazzband/geojson/blob/main/_autodocs/types.md Uses the `generate_random` utility to create a Point within specified geographic bounds. The default bounds cover the entire world. ```python from geojson.utils import generate_random # World bounds (default) bounds = [-180.0, -90.0, 180.0, 90.0] point = generate_random("Point", boundingBox=bounds) # New York area ny_bounds = [-74.3, 40.5, -73.7, 40.9] ny_point = generate_random("Point", boundingBox=ny_bounds) ``` -------------------------------- ### Create Polygon objects Source: https://github.com/jazzband/geojson/blob/main/docs/source/index.md Create Polygon objects, demonstrating both polygons without holes and with holes. The output shows their respective JSON representations. ```python >>> 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)]]) {"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)] ... ]) {"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"} ``` -------------------------------- ### LineString Constructor with Coordinate Tuples Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Creates a LineString from a list of coordinate tuples. ```python from geojson import LineString, Point # List of coordinate tuples line = LineString([(-115.81, 37.24), (-115.82, 37.25)]) ``` -------------------------------- ### Create FeatureCollection with dictionaries Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md Instantiate a FeatureCollection using a list of dictionaries that conform to the GeoJSON Feature structure. These dictionaries are automatically converted to Feature class instances. ```python from geojson import FeatureCollection, Feature, Point # With dictionaries feature_dicts = [ {"type": "Feature", "geometry": {"type": "Point", "coordinates": [0, 0]}, "properties": {}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [1, 1]}, "properties": {}} ] fc = FeatureCollection(feature_dicts) ``` -------------------------------- ### Support Classes Source: https://github.com/jazzband/geojson/blob/main/_autodocs/README.md Base classes and utility classes for GeoJSON object handling. ```APIDOC ## GeoJSON ### Description Base class for all GeoJSON objects, providing dict-like access and GeoJSON methods. ### Class Definition `geojson.base.GeoJSON` ``` ```APIDOC ## GeoJSONEncoder ### Description A custom JSON encoder for GeoJSON objects. ### Class Definition `geojson.codec.GeoJSONEncoder` ``` ```APIDOC ## to_mapping ### Description Convert GeoJSON objects to a dictionary-like mapping. ### Signature to_mapping(obj) ### Parameters - **obj**: The GeoJSON object to convert. ``` ```APIDOC ## is_mapping ### Description Check if an object is a dictionary-like mapping. ### Signature is_mapping(obj) ### Parameters - **obj**: The object to check. ``` -------------------------------- ### Import Core GeoJSON Components Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md Import essential classes and functions from the main geojson module. These are the building blocks for creating and manipulating GeoJSON objects. ```python from geojson import Point, Feature, dump, dumps, load, loads, coords, map_coords, __version__ ``` -------------------------------- ### Point Constructor Source: https://github.com/jazzband/geojson/blob/main/_autodocs/api-reference/geometry.md Defines the constructor for the Point class, specifying parameters for coordinates, validation, precision, and extra properties. ```python class Point(Geometry): def __init__(self, coordinates=None, validate=False, precision=None, **extra) ``` -------------------------------- ### Serialization: dump() and dumps() Source: https://github.com/jazzband/geojson/blob/main/_autodocs/configuration.md These functions serialize Python objects into GeoJSON format. `dumps` returns a string, while `dump` writes to a file-like object. They accept standard JSON options and GeoJSON-specific options like `allow_nan`. ```APIDOC ## dump() and dumps() ### Description Serializes a Python object to a GeoJSON formatted string or file. ### Methods - `dump(obj, fp, cls=GeoJSONEncoder, allow_nan=False, **kwargs)`: Writes the GeoJSON representation of `obj` to the file-like object `fp`. - `dumps(obj, cls=GeoJSONEncoder, allow_nan=False, ensure_ascii=False, **kwargs)`: Returns the GeoJSON representation of `obj` as a string. ### Parameters #### Standard JSON Options (passed through to json module): - `indent`: Int or None — Pretty-print with indentation (None for compact output) - `sort_keys`: Bool — Sort object keys in output - `separators`: Tuple — Custom `(item_separator, key_separator)` - `default`: Callable — Custom encoder for non-serializable objects - `skipkeys`: Bool — Skip non-string keys - `cls`: JSONEncoder subclass — Custom encoder class #### GeoJSON-specific Options: - `allow_nan`: Bool (default `False`) — Allow NaN/Infinity values (strict RFC 4267 compliance when False) ### Request Example ```python import geojson point = geojson.Point((-115.81, 37.24)) # Compact output json_str = geojson.dumps(point) # Pretty-printed output json_str = geojson.dumps(point, indent=2, sort_keys=True) # Write to file with open('output.json', 'w') as f: geojson.dump(point, f, indent=2) ``` ``` -------------------------------- ### Create a LineString object Source: https://github.com/jazzband/geojson/blob/main/docs/source/index.md Create a LineString object from a list of coordinate pairs. The output shows the JSON representation of the LineString. ```python >>> from geojson import LineString >>> LineString([(8.919, 44.4074), (8.923, 44.4075)]) {"coordinates": [[8.91..., 44.407...], [8.92..., 44.407...]], "type": "LineString"} ``` -------------------------------- ### __version_info__ Source: https://github.com/jazzband/geojson/blob/main/_autodocs/PUBLIC_API.md The version of the geojson library as a tuple of integers. ```APIDOC ## __version_info__ ### Description Version as tuple of integers. ### Type ```python tuple ``` ### Value ```python (3, 3, 0) ``` ```