Created
September 28, 2016 00:23
-
-
Save mgd020/14072580ddd69cd35a08ad6fa89b98a5 to your computer and use it in GitHub Desktop.
A haystack search field for specifying multiple locations for a single document.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import absolute_import, division, print_function, unicode_literals | |
import six | |
from django.contrib.gis.geos import Point | |
from haystack import indexes | |
from haystack.exceptions import SpatialError | |
from haystack.utils.geo import ensure_geometry, ensure_point | |
def ensure_multipoint(geom): | |
"""Make sure the parameter passed in looks like a GEOS ``MultiPoint``.""" | |
ensure_geometry(geom) | |
if geom.geom_type != 'MultiPoint': | |
raise SpatialError("Provided geometry '%s' is not a 'MultiPoint'." % geom) | |
return geom | |
class MultiLocationField(indexes.SearchField): | |
""" | |
A field for specifying multiple locations for a single document. | |
Spatial queries will include the document if any of the points in | |
the MultiPointField match the query. | |
Input can be a MultiPoint GEOS geometry object, an array of Point GEOS geometry objects, | |
or a sequence of any representation of a Point object recognized by the built-in LocationField | |
((lat,long) tuples, {"lat": lat, "long": long} dictionary, or "lat,long" string.) | |
Works with elasticsearch backend for sure. Haven't tested with other backends. | |
""" | |
field_type = 'location' | |
def __init__(self, **kwargs): | |
super(MultiLocationField, self).__init__(**kwargs) | |
self.is_multivalued = True | |
def prepare(self, obj): | |
value = super(MultiLocationField, self).prepare(obj) | |
if value is None: | |
return None | |
points = [] | |
for point in value: | |
pnt = ensure_point(value) | |
pnt_lng, pnt_lat = pnt.get_coords() | |
points.appen("%s,%s" % (pnt_lat, pnt_lng)) | |
return points | |
def convert(self, value): | |
if value is None: | |
return None | |
if hasattr(value, 'geom_type'): | |
value = ensure_multipoint(value) | |
value = [Point(coord[0], coord[1]) for coord in value.coords] | |
return value | |
points = [] | |
for point in value: | |
if hasattr(point, 'geom_type'): | |
points.append(ensure_point(value)) | |
continue | |
if isinstance(point, six.string_types): | |
lat, lng = point.split(',') | |
elif isinstance(point, (list, tuple)): | |
# GeoJSON-alike | |
lat, lng = point[1], point[0] | |
elif isinstance(point, dict): | |
lat = point.get('lat', 0) | |
lng = point.get('lon', 0) | |
points.append(Point(float(lng), float(lat))) | |
return points |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment