This is a continuation of part I.
Converting phrases into coordinates
Let’s test out Nominatim – the Open Street Maps tool to search their map data. We basically want whatever the user types in to turn into map coordinates.
from geopy.geocoders import Nominatim from django.contrib.gis.geos import Point def words_to_point(q): geolocator = Nominatim() location = geolocator.geocode(q) point = Point(location.longitude, location.latitude) return point
We can take vague statements like New York and get the coordinates of New York City. So easy!
Putting things together
I’ll use Django Rest Framework to make an api where we can query this data and return json. I’m leaving out some scaffolding code – so make sure you are familiar with Django Rest Framework first – or just make your own view without it.
class LocationViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): """ Searchable list of locations GET params: - q - Location search paramater (New York or 10001) - distance - Distance away. Defaults to 50 """ serializer_class = LocationSerializer queryset = Location.objects.all() def get_queryset(self, *args, **kwargs): queryset = self.queryset q = self.request.GET.get('q') distance = self.request.GET.get('distance', 50) if q: point = words_to_point(q) distance = D(mi=distance) queryset = queryset.filter(point__distance_lte=(point, distance)) return queryset
At this point we have a usable backend. Next steps would be to pick a client side solution to present this data. I might post more on that later.