| 1 |
import json |
| 2 |
from collections import OrderedDict |
| 3 |
|
| 4 |
from django.contrib.gis.gdal import GDALException |
| 5 |
from django.contrib.gis.geos import GEOSException, GEOSGeometry |
| 6 |
from django.core.exceptions import ValidationError |
| 7 |
from django.utils.translation import gettext_lazy as _ |
| 8 |
from rest_framework.fields import Field, SerializerMethodField |
| 9 |
|
| 10 |
__all__ = ["GeometryField", "GeometrySerializerMethodField"] |
| 11 |
|
| 12 |
|
| 13 |
class GeometryField(Field): |
| 14 |
""" |
| 15 |
A field to handle GeoDjango Geometry fields |
| 16 |
""" |
| 17 |
|
| 18 |
type_name = "GeometryField" |
| 19 |
|
| 20 |
def __init__( |
| 21 |
self, |
| 22 |
precision=None, |
| 23 |
remove_duplicates=False, |
| 24 |
auto_bbox=False, |
| 25 |
transform=None, |
| 26 |
**kwargs, |
| 27 |
): |
| 28 |
""" |
| 29 |
:param auto_bbox: Whether the GeoJSON object should include a bounding box |
| 30 |
""" |
| 31 |
self.precision = precision |
| 32 |
self.auto_bbox = auto_bbox |
| 33 |
self.remove_dupes = remove_duplicates |
| 34 |
self.transform = transform |
| 35 |
super().__init__(**kwargs) |
| 36 |
self.style.setdefault("base_template", "textarea.html") |
| 37 |
|
| 38 |
def to_representation(self, value): |
| 39 |
if isinstance(value, dict) or value is None: |
| 40 |
return value |
| 41 |
# we expect value to be a GEOSGeometry instance |
| 42 |
if value.geojson: |
| 43 |
# NOTE: For repeated transformations a gdal.CoordTransform is recommended |
| 44 |
if self.transform is not None and value.srid is not None: |
| 45 |
value.transform(self.transform) |
| 46 |
|
| 47 |
geojson = GeoJsonDict(value.geojson) |
| 48 |
# in this case we're dealing with an empty point |
| 49 |
else: |
| 50 |
geojson = GeoJsonDict({"type": value.geom_type, "coordinates": []}) |
| 51 |
if geojson["type"] == "GeometryCollection": |
| 52 |
geometries = geojson.get("geometries") |
| 53 |
else: |
| 54 |
geometries = [geojson] |
| 55 |
for geometry in geometries: |
| 56 |
if self.precision is not None: |
| 57 |
geometry["coordinates"] = self._recursive_round( |
| 58 |
geometry["coordinates"], self.precision |
| 59 |
) |
| 60 |
if self.remove_dupes: |
| 61 |
geometry["coordinates"] = self._rm_redundant_points( |
| 62 |
geometry["coordinates"], geometry["type"] |
| 63 |
) |
| 64 |
if self.auto_bbox: |
| 65 |
geojson["bbox"] = value.extent |
| 66 |
return geojson |
| 67 |
|
| 68 |
def to_internal_value(self, value): |
| 69 |
if value == "" or value is None: |
| 70 |
return value |
| 71 |
if isinstance(value, GEOSGeometry): |
| 72 |
# value already has the correct representation |
| 73 |
return value |
| 74 |
if isinstance(value, dict): |
| 75 |
value = json.dumps(value) |
| 76 |
try: |
| 77 |
return GEOSGeometry(value) |
| 78 |
except GEOSException: |
| 79 |
raise ValidationError( |
| 80 |
_( |
| 81 |
"Invalid format: string or unicode input unrecognized as GeoJSON, WKT EWKT or HEXEWKB." |
| 82 |
) |
| 83 |
) |
| 84 |
except (ValueError, TypeError, GDALException) as e: |
| 85 |
raise ValidationError(_(f"Unable to convert to python object: {str(e)}")) |
| 86 |
|
| 87 |
def validate_empty_values(self, data): |
| 88 |
if data == "": |
| 89 |
self.fail("required") |
| 90 |
return super().validate_empty_values(data) |
| 91 |
|
| 92 |
def _recursive_round(self, value, precision): |
| 93 |
""" |
| 94 |
Round all numbers within an array or nested arrays |
| 95 |
value: number or nested array of numbers |
| 96 |
precision: integer valueue of number of decimals to keep |
| 97 |
""" |
| 98 |
if hasattr(value, "__iter__"): |
| 99 |
return tuple(self._recursive_round(v, precision) for v in value) |
| 100 |
return round(value, precision) |
| 101 |
|
| 102 |
def _rm_redundant_points(self, geometry, geo_type): |
| 103 |
""" |
| 104 |
Remove redundant coordinate pairs from geometry |
| 105 |
geometry: array of coordinates or nested-array of coordinates |
| 106 |
geo_type: GeoJSON type attribute for provided geometry, used to |
| 107 |
determine structure of provided `geometry` argument |
| 108 |
""" |
| 109 |
if geo_type in ("MultiPoint", "LineString"): |
| 110 |
close = geo_type == "LineString" |
| 111 |
output = [] |
| 112 |
for coord in geometry: |
| 113 |
coord = tuple(coord) |
| 114 |
if not output or coord != output[-1]: |
| 115 |
output.append(coord) |
| 116 |
if close and len(output) == 1: |
| 117 |
output.append(output[0]) |
| 118 |
return tuple(output) |
| 119 |
if geo_type in ("MultiLineString", "Polygon"): |
| 120 |
return [self._rm_redundant_points(c, "LineString") for c in geometry] |
| 121 |
if geo_type == "MultiPolygon": |
| 122 |
return [self._rm_redundant_points(c, "Polygon") for c in geometry] |
| 123 |
return geometry |
| 124 |
|
| 125 |
|
| 126 |
class GeometrySerializerMethodField(SerializerMethodField): |
| 127 |
def to_representation(self, value): |
| 128 |
value = super().to_representation(value) |
| 129 |
if value is not None: |
| 130 |
# we expect value to be a GEOSGeometry instance |
| 131 |
return GeoJsonDict(value.geojson) |
| 132 |
else: |
| 133 |
return None |
| 134 |
|
| 135 |
|
| 136 |
class GeoJsonDict(OrderedDict): |
| 137 |
""" |
| 138 |
Used for serializing GIS values to GeoJSON values. |
| 139 |
""" |
| 140 |
|
| 141 |
def __init__(self, *args, **kwargs): |
| 142 |
""" |
| 143 |
If a string is passed attempt to pass it through json.loads, |
| 144 |
because it should be a geojson formatted string. |
| 145 |
""" |
| 146 |
if args and isinstance(args[0], str): |
| 147 |
try: |
| 148 |
geojson = json.loads(args[0]) |
| 149 |
args = (geojson,) |
| 150 |
except ValueError: |
| 151 |
pass |
| 152 |
super().__init__(*args, **kwargs) |
| 153 |
|
| 154 |
def __str__(self): |
| 155 |
""" |
| 156 |
Avoid displaying strings like |
| 157 |
``{ 'type': u'Point', 'coordinates': [12, 32] }`` |
| 158 |
in DRF browsable UI inputs (python 2.6/2.7) |
| 159 |
see: https://github.com/openwisp/django-rest-framework-gis/pull/60 |
| 160 |
""" |
| 161 |
return json.dumps(self) |