GeoJSON support for Django GraphQL
- Python ≥ 3.4
- Django ≥ 1.11
Install last stable version from Pypi.
GeoJSONType
is a subclass of DjangoObjectType
which provides GraphQL fields in GeoJSON format.
Just define a Meta.geojson_field
to be represented as a Geometry
type.
models.py
schema.py
Query
query {
places {
id
type
geometry {
type
coordinates
}
bbox
properties {
name
}
}
}
Geometry
is a special GraphQL type that represents a GEOS geometry object.
schema.py
import graphene
import graphql_geojson
class CreatePlace(graphene.Mutation):
place = graphene.Field(types.PlaceType)
class Arguments:
name = graphene.String(required=True)
location = graphql_geojson.Geometry(required=True)
@classmethod
def mutate(cls, root, info, **args):
place = models.Place.objects.create(**args)
return cls(place=place)
Mutation
mutation CreatePlace($name: String!, $location: Geometry!) {
createPlace(name: $name, location: $location) {
place {
id
}
}
}
Geometry
type may be initialized in a few ways:
- Well-known text (WKT):
- Hexadecimal (HEX):
- GeoJSON:
Django GraphQL GeoJSON provides a custom FilterSet for spatial lookups.
The Meta.fields
option is combined with model to automatically generate filters.
filters.py
schema.py
import graphene
import graphql_geojson
from graphene import relay
from graphene_django.filter import DjangoFilterConnectionField
class PlaceNode(graphql_geojson.GeoJSONType):
class Meta:
model = Place
interfaces = [relay.Node]
geojson_field = 'location'
class Query(graphene.ObjectType):
places = DjangoFilterConnectionField(
PlaceNode,
filterset_class=PlaceFilter)
Query
query Places($geometry: Geometry!){
places(location_Intersects: $geometry) {
edges {
node {
id
}
}
}
}
Distance lookups take a Distance
parameter comprising:
- The desired unit attribute name
- Distance value
- A geometry to base calculations from
query Places(
$unit: DistanceUnitEnum!,
$value: Float!,
$geometry: Geometry!)
{
places(location_DistanceLte: {
unit: $unit,
value: $value,
geometry: $geometry
}) {
edges {
node {
id
}
}
}
}
If you have a problem don't hesitate to ask for assistance.