Manage your XYZ Hub or HERE Data Hub spaces from Python.

Overview

XYZ Spaces for Python

Documentation Status Tests PyPI - Status PyPI - Python Version PyPI - Implementation Downloads Conda (channel only) Conda Downloads PyPI - License LGTM alerts LGTM context Swagger Validator GitHub contributors Codecov Slack Code style: black commits since Anaconda-Server Badge Binder

Manage your XYZ Hub or HERE Data Hub spaces and Interactive Map Layer from Python.

FEATURED IN: Online Python Machine Learning Conference & GeoPython 2020, Sept 21, 2020, see conference schedule.

Motivation

XYZ is an Open Source, real-time, cloud database system providing access to large geospatial data at scale. An XYZ "Hub" manages "spaces" that contain "features" (geodata "records") with tags and properties, with spaces and features having unique IDs. A RESTful API exists to provide low-level access to interact with a XYZ Hub.

This Python package allows to interact with your XYZ spaces and features on a given Hub using a higher level programmatic interface that wraps the RESTful API. Using this package you can:

  • Create, read, list, update, share, delete spaces (also: get space info and stats).
  • Add, read, update, iterate, search, cluster (hex/quad bins), delete features.
  • Search features by ID, tag, property, bbox, tile, radius, geometry.

Based on the XYZ Hub the HERE Data Hub is a commercial service (with a free plan), that offers some additional features (in a pro plan), like clustering, virtual spaces, activity logs, and likely more to come.

The GIF below shows an interaction with an example notebook, demonstrating how to use a spatial search on a big public dataset, loaded from the HERE Data Hub.

Example from xyzspaces building_numbers.ipynb notebook

Prerequisites

Before you can install this package, run its test-suite or use the example notebooks to make sure your system meets the following prerequisities:

  • A Python installation, 3.7+ recommended, with the pip command available to install dependencies

  • A HERE developer account, free and available under HERE Developer Portal

  • An XYZ API access token from your XYZ Hub server or the XYZ portal (see also its Getting Started section) in an environment variable named XYZ_TOKEN which you can set like this (with a valid value, of course):

    export XYZ_TOKEN="MY-FANCY-XYZ-TOKEN"

    If you prefer, you can alternatively provide this token as a parameter in your code.

Installation

This package can be installed with pip or conda from various sources:

  • Install with conda from the Anaconda conda-forge channel:

    conda install -c conda-forge xyzspaces
  • Install from the Python Package Index:

    pip install xyzspaces
  • Install from the Python Package Index with optional dependencies:

    pip install "xyzspaces[geo]"
  • Install from its source repository on GitHub:

    pip install -e git+https://github.com/heremaps/xyz-spaces-python#egg=xyzspaces

If you want to run the test suite or experiment with the example notebooks bundled, you need to clone the whole repository:

  • Make a local clone of the repository hosting this package. The following command should do:

    git clone https://github.com/heremaps/xyz-spaces-python.git
  • Change into the repo root directory:

    cd xyzspaces

Interactive Map Layers

The xyzspaces package supports Interactive Map Layers which is Data Hub on HERE Platform. Using xyzspaces you can interact with your Interactive Map Layers using higher level pythonic interface that wraps the RESTful API. With Interactive Map Layers, data is stored in GeoJSON and can be retrieved dynamically at any zoom level. Interactive map layer is optimized for the visualization, analysis, and modification of data on a map (i.e., GIS functions).

Key features of Interactive Map Layers include:

  • Creating and modifying maps manually or programmatically; edits are published real-time and require no additional interaction.
  • Modifying data a granular feature and feature property level.
  • Adding and removing points, lines, and polygons directly on a map.
  • Ability to retrieve data in different tiling schemes.
  • Exploring and retrieving data by feature ID, bounding box, spatial search, property search, and features contained within a tile.
  • Searching for data by values of feature properties (e.g., speed limits, type of place, address, name, etc.).
  • Data sampling, making it possible to efficiently render an excerpt of a very large data set for visual reference and analysis.
  • Clustering using hexbins or quadbins to produce rich, visual data representations.

Credentials

To interact with Interactive Map Layer you will need an account on the HERE Platform. To get more details on the HERE Platform account please check our documentation Get a HERE account. Once you have the account follow the below steps to get credentials:

The HERE platform generated app credentials should look similar to the example below:

  here.user.id = <example_here>
  here.client.id = <example_here>
  here.access.key.id = <example_here>
  here.access.key.secret = <example_here>
  here.token.endpoint.url = <example_here>

You can provide your credentials using any of the following methods:

  • Default credentials
  • Environment variables
  • Credentials file

Default credentials

Place the credentials file into

For Linux/MacOS: $HOME/.here/credentials.properties

For Windows: %USERPROFILE%\.here\credentials.properties

Environment Variables

You can override default credentials by assigning values to the following environment variables:

HERE_USER_ID
HERE_CLIENT_ID
HERE_ACCESS_KEY_ID
HERE_ACCESS_KEY_SECRET
HERE_TOKEN_ENDPOINT_URL

Credentials File

You can specify any credentials file as an alternative to that found in ~/.here/credentials.properties. An error is generated if there is no file present at the path, or if the file is not properly formatted.

Documentation

Documentation is hosted here.

To build the docs locally run:

bash scripts/build_docs.sh

Hello World Example

The following are tiny "Hello World"-like examples that you can run to have a successful first XYZ experience right after installation!

Data Hub

import geojson
import os
import xyzspaces

os.environ["XYZ_TOKEN"] = "MY_XYZ_TOKEN"
xyz = xyzspaces.XYZ()

# Create a New Space
title = "My Demo Space"
description = "My Description"
space = xyz.spaces.new(title=title, description=description)

# Define a New Feature
feature =  {
    "type": "Feature",
    "properties": {"party": "Republican"},
    "geometry": {
        "type": "Polygon",
        "coordinates": [[
            [-104.05, 48.99],
            [-97.22,  48.98],
            [-96.58,  45.94],
            [-104.03, 45.94],
            [-104.05, 48.99]
        ]]
    }
}

# Save it to a Space and get its ID
feature_id = space.add_features(features=geojson.FeatureCollection([feature]))["features"][0]["id"]

# Read a Feature from a Space
feature = space.get_feature(feature_id=feature_id)
print(geojson.dumps(feature, indent=4, sort_keys=True))

Interactive Map Layer

import geojson
from xyzspaces import IML
from xyzspaces.iml.credentials import Credentials

credentials = Credentials.from_default() # credentials are in either credentials file at default location or in environment variables

layer_details = {
    "id": "demo-interactive-layer",
    "name": "Demo Interactive Layer",
    "summary": "Demo Interactive Layer",
    "description": "Demo Interactive Layer",
    "layerType": "interactivemap",
    "interactiveMapProperties": {},
}

iml = IML.new(
    catalog_id="demo-catalog1",
    catalog_name="demo-catalog",
    catalog_summary="Demo catalog",
    catalog_description="Demo catalog",
    layer_details=layer_details,
    credentials=credentials,
)

# Define a New Feature
feature = {
    "type": "Feature",
    "properties": {"party": "Republican"},
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                [-104.05, 48.99],
                [-97.22, 48.98],
                [-96.58, 45.94],
                [-104.03, 45.94],
                [-104.05, 48.99],
            ]
        ],
    },
}
# Save feature to interactive map layer
iml.layer.write_feature(feature_id="demo_feature", data=feature)

# Read feature from nteractive map layer
resp = iml.layer.get_feature(feature_id="demo_feature")
print(geojson.dumps(resp.to_geojson(), indent=4, sort_keys=True))

License

Copyright (C) 2019-2021 HERE Europe B.V.

Unless otherwise noted in LICENSE files for specific directories, the LICENSE in the root applies to all content in this repository.

Comments
  • Outdated package on conda-forge?

    Outdated package on conda-forge?

    Hi guys, I wanted to let you know that I recently installed xyzspace package from conda-forge (version '0.4.0') and it looks that some functionalities are missing there. E.g. according to the documentation one of the parameters of space.spatial_search() is 'force_2d' (to skip Z coordinate in the response). When I wanted to use it I got: TypeError: spatial_search() got an unexpected keyword argument 'force_2d'

    Thanks, Piotr

    no-issue-activity 
    opened by pioboch 4
  • Feature request: 'params' query for feature filtering

    Feature request: 'params' query for feature filtering

    Please implement the functionality to filter feature based in the Python client. A feature filter contains 3 components: property name, value and operator. The current implementation is not sufficient when one want to filter feature using an operator other than equal '='

    Feature filtering is realized in XYZ API via 'params' query for several endpoint, for example for tile request https://xyz.api.here.com/hub/static/swagger/#/Read%20Features/getFeaturesByTile

    Query Syntax ?p.property_name_1=value_1,value_2

    Supported operators

    "=" - equals
    "!=" - not equals
    ">=" or "=gte=" - greater than or equals
    "<=" or "=lte=" - less than or equals
    ">" or "=gt=" - greater than
    "<" or "=lt=" - less than
    "@>" or "=cs=" - contains
    

    Thank you

    enhancement 
    opened by minff 4
  • Exclude tests submodules from package

    Exclude tests submodules from package

    With current setup.py, pip install would still install "tests" package at the same level as xyzspaces package. Added wildcard pattern to exclude it

    opened by minff 3
  • Add initial ADRs

    Add initial ADRs

    Initial stab at adding ADRs, as described by Michael Nygard. This is in MD, but later down the line we might explore way to include this into the main documentation which is formatted in ReST...

    opened by deeplook 3
  • Added changes for custom url for self hosted data hub instances

    Added changes for custom url for self hosted data hub instances

    Signed-off-by: Kharude, Sachin [email protected]

    This PR includes changes for private instances of DataHub APIs. With this change, the user can provide a different base URL for self-hosted Data Hub APIs.

    opened by sackh 2
  • Consider suppressing returning resources for PUT/POST requests

    Consider suppressing returning resources for PUT/POST requests

    Using Accept: application/x-empty in PUT/POST feature requests would prevent the resource to be returned again in the HTTP response which would save some bandwidth and might even reduce server load a bit. If the user really wants the resource it can be obtained with a follow-up GET request.

    enhancement no-issue-activity 
    opened by deeplook 2
  • Resolution param for hexbin clusters has no effect

    Resolution param for hexbin clusters has no effect

    Sample snippet:

    from ipyleaflet import GeoJSON, Map
    from turfpy.measurement import center
    from xyzspaces import XYZ
    from xyzspaces.datasets import get_countries_data
    
    xyz_pro_token = "******"
    xyz = XYZ(credentials=xyz_pro_token)
    space = xyz.spaces.new(title="Hexbin Cluster Demo", description="Hexbin Cluster Demo")
    afg = get_countries_data()["features"][0]
    space.add_features(features=geojson.FeatureCollection([afg]))
    try:
        fc = None
        # Allowed params: [resolution, relativeResolution, absoluteResolution,
        #                  property, pointmode, countmode, noBuffer]
        fc = space.cluster("hexbin", clustering_params={"absoluteResolution": 5})
    finally:
        space.delete()
    
    c = list(reversed(center(afg)["geometry"]["coordinates"]))
    m = Map(center=c, zoom=5)
    if fc:
        m += GeoJSON(data=fc)
    m
    
    opened by deeplook 2
  • Added clientId in query params for Hub API requests

    Added clientId in query params for Hub API requests

    Signed-off-by: Kharude, Sachin [email protected]

    • Added clientId in query params as suggested by DataHub developers this helps in identifying requests sent from xyzspaces library.
    • Minor variable name changes as per pep8 guidelines.
    • Improved clean up for activity log test.
    opened by sackh 2
  • Fix: added mode and viz_sampling params in space class method features_in_tile

    Fix: added mode and viz_sampling params in space class method features_in_tile

    This PR fixes two missing parameters in the Space class's method features_in_tile, mode and viz_sampling which were present in the Api class's method get_space_tile. Also added missing proclamation changes.

    opened by sackh 1
Releases(v0.7.2)
  • v0.7.2(Aug 18, 2021)

  • v0.7.1(Aug 10, 2021)

  • v0.7.0(Aug 10, 2021)

  • v0.6.0(Jun 17, 2021)

  • 0.5.0(Feb 1, 2021)

    Features

    • Added functionality to clone Space. (#93)
    • Added support for the new force2D parameter for all the APIs used to read features. (#96)
    • Added support for new mode and vizSampling params in HubApi.get_space_tile. (#101)
    Source code(tar.gz)
    Source code(zip)
  • 0.4.0(Sep 18, 2020)

    Features

    • Upload data from kml and geobuff files to space.
    • Upload Geopandas Dataframe to space and read space data as Geopandas Dataframe.
    • Enabled property search while searching features in the bounding box.
    • Enabled property search while searching features in tile.
    • Improved performance of CSV and GeoJSON files upload.
    • Enabled conversion of original projection of shapefile to EPSG:4326.
    • New notebook illustrating spatial search on Microsoft US building footprints dataset.

    Fixes:

    • Fixed encoding and projections issue for shapefile upload.
    • Fixed duplicate features for spatial_search_geometry with the division.
    • Fixed upload of duplicate features while uploading to space using add_features.
    • Madedescription param optional when creating the space.
    • Added limit param to method iter_feature of Space class to control the number of features to iterate in a single call.
    Source code(tar.gz)
    Source code(zip)
  • 0.3.2(Aug 19, 2020)

    Features

    Upload Enhancements:

    • Supporting upload via shapefile to space. (#40)
    • Supporting upload via WKT file to space. (#41)
    • Supporting upload via gpx file to space. (#42)

    Optimized the spatial search to search features from large geometries. (#44)

    Misc

    • Added Binder support to the repository. (#28)
    Source code(tar.gz)
    Source code(zip)
  • 0.3.1(Jul 24, 2020)

  • 0.3(Jul 24, 2020)

Owner
HERE Technologies
HERE Technologies, the leading location cloud.
HERE Technologies
PySAL: Python Spatial Analysis Library Meta-Package

Python Spatial Analysis Library PySAL, the Python spatial analysis library, is an open source cross-platform library for geospatial data science with

Python Spatial Analysis Library 1.1k Dec 18, 2022
Calculate & view the trajectory and live position of any earth-orbiting satellite

satellite-visualization A cross-platform application to calculate & view the trajectory and live position of any earth-orbiting satellite in 3D. This

Space Technology and Astronomy Cell - Open Source Society 3 Jan 08, 2022
pure-Python (Numpy optional) 3D coordinate conversions for geospace ecef enu eci

Python 3-D coordinate conversions Pure Python (no prerequistes beyond Python itself) 3-D geographic coordinate conversions and geodesy. API similar to

Geospace code 292 Dec 29, 2022
A service to auto provision devices in Aruba Central based on the Geo-IP location

Location Based Provisioning Service for Aruba Central A service to auto provision devices in Aruba Central based on the Geo-IP location Geo-IP auto pr

Will Smith 3 Mar 22, 2022
Rasterio reads and writes geospatial raster datasets

Rasterio Rasterio reads and writes geospatial raster data. Geographic information systems use GeoTIFF and other formats to organize and store gridded,

Mapbox 1.9k Jan 07, 2023
Digital Earth Australia notebooks and tools repository

Repository for Digital Earth Australia Jupyter Notebooks: tools and workflows for geospatial analysis with Open Data Cube and xarray

Geoscience Australia 335 Dec 24, 2022
iNaturalist observations along hiking trails

This tool reads the route of a hike and generates a table of iNaturalist observations along the trails. It also shows the observations and the route of the hike on a map. Moreover, it saves waypoints

7 Nov 11, 2022
Expose a GDAL file as a HTTP accessible on-the-fly COG

cogserver Expose any GDAL recognized raster file as a HTTP accessible on-the-fly COG (Cloud Optimized GeoTIFF) The on-the-fly COG file is not material

Even Rouault 73 Aug 04, 2022
:earth_asia: Python Geocoder

Python Geocoder Simple and consistent geocoding library written in Python. Table of content Overview A glimpse at the API Forward Multiple results Rev

Denis 1.5k Jan 02, 2023
Location field and widget for Django. It supports Google Maps, OpenStreetMap and Mapbox

django-location-field Let users pick locations using a map widget and store its latitude and longitude. Stable version: django-location-field==2.1.0 D

Caio Ariede 481 Dec 29, 2022
Starlite-tile38 - Showcase using Tile38 via pyle38 in a Starlite application

Starlite-Tile38 Showcase using Tile38 via pyle38 in a Starlite application. Repo

Ben 8 Aug 07, 2022
A part of HyRiver software stack for handling geospatial data manipulations

Package Description Status PyNHD Navigate and subset NHDPlus (MR and HR) using web services Py3DEP Access topographic data through National Map's 3DEP

Taher Chegini 5 Dec 14, 2022
Summary statistics of geospatial raster datasets based on vector geometries.

rasterstats rasterstats is a Python module for summarizing geospatial raster datasets based on vector geometries. It includes functions for zonal stat

Matthew Perry 437 Dec 23, 2022
Wraps GEOS geometry functions in numpy ufuncs.

PyGEOS PyGEOS is a C/Python library with vectorized geometry functions. The geometry operations are done in the open-source geometry library GEOS. PyG

362 Dec 23, 2022
Record railway train route profile with GNSS tools

Train route profile recording with GNSS technology based on ARDUINO platform Project target Develop GNSS recording tools based on the ARDUINO platform

tomcom 1 Jan 01, 2022
glTF to 3d Tiles Converter. Convert glTF model to Glb, b3dm or 3d tiles format.

gltf-to-3d-tiles glTF to 3d Tiles Converter. Convert glTF model to Glb, b3dm or 3d tiles format. Usage λ python main.py --help Usage: main.py [OPTION

58 Dec 27, 2022
WIP: extracting Geometry utilities from datacube-core

odc.geo This is still work in progress. This repository contains geometry related code extracted from Open Datacube. For details and motivation see OD

Open Data Cube 34 Jan 09, 2023
Python bindings and utilities for GeoJSON

geojson This Python library contains: Functions for encoding and decoding GeoJSON formatted data Classes for all GeoJSON Objects An implementation of

Jazzband 765 Jan 06, 2023
Stitch image tiles into larger composite TIFs

untiler Utility to take a directory of {z}/{x}/{y}.(jpg|png) tiles, and stitch into a scenetiff (tif w/ exact merc tile bounds). Future versions will

Mapbox 38 Dec 16, 2022
Deal with Bing Maps Tiles and Pixels / WGS 84 coordinates conversions, and generate grid Shapefiles

PyBingTiles This is a small toolkit in order to deal with Bing Tiles, used i.e. by Facebook for their Data for Good datasets. Install Clone this repos

Shoichi 1 Dec 08, 2021