Geopy ValueError "Failed to find exactly one match" when geocoding

In Django, I am trying to find a search field for geocoding a location and spit out a list from my db sorted by distance. So far, everything works, except when I'm looking for a location where Google returns multiple forms of results, such as "ann arbor, MI". I get a ValueError "I did not find exactly one label! (Found 2.)" Here is my view.py

from django.shortcuts import render_to_response
from models import CampSite
from geopy import geocoders
from django.contrib.gis.geos import *
from django.contrib.gis.measure import D
from campsites.forms import SearchForm
from django.http import HttpResponseRedirect


def results(request):
    query = request.GET['q']
    g = geocoders.Google(resource='maps')
    location, (lat, lon) = g.geocode(query) 
    pnt = fromstr("POINT(%s %s)" % (lon, lat))
    distance_from_point = {'mi':'2000'}
    results = CampSite.objects.filter(lonlat__distance_lte=(pnt,D(**distance_from_point))).distance(pnt).order_by('distance')
    return render_to_response('results.html',{'location': location, 'lat': lat, 'lon': lon, 'results':results})

The common solution I found on the Internet was to change

location, (lat, lon) = g.geocode(query)


to


location, (lat, lon) = g.geocode(query, exactly_one=False)

However, this led to the emergence of a new ValueError value of "String or unicode not recognized as WKT EWKT and HEXEWKB."

This is my first django project that I do outside of the tutorials, so thanks for being gentle.

+5
1

Python - .

>>> g.geocode('ann arbor, MI', exactly_one=False)
[(u'Ann Arbor, MI, USA', (42.2808256, -83.743037799999996)),
 (u'Ann Arbor, MI, USA', (42.307649300000001, -83.8473015))]

, , exact_one = False , , .

results = []
geocodes = g.geocode(query, exactly_one=False)
for geocode in geocodes:
    location, (lat, lon) = geocode
    pnt = fromstr("POINT(%s %s)" % (lon, lat))
    distance_from_point = {'mi':'2000'}
    results.append(
        CampSite.objects.filter(
             lonlat__distance_lte=(
                  pnt,
                  D(**distance_from_point)
             )
        ).distance(pnt).order_by('distance')
    )

, . , :

  • (geocodes[0], results[0])
  • ( zip(geocodes, results) )
+5

All Articles