Search code examples
pythonjupyter-notebookgeopy

Using Geopy in a Jupyter notebook - my lambda query isn't functioning


I'm using Geopy in a Jupyter Notebook and Python. I want to retrieve latitude and longitude for street addresses. I'd like to limit the query to Texas and the lambda code isn't working...can anybody help? Even using "Houston, Tx" doesn't work. The street address is "1931 Santa Rosa, Houston, Tx 77023".

#pip install geopy   #https://geopy.readthedocs.io/en/latest/
from geopy.geocoders import Nominatim
from functools import partial
import urllib.parse

geocode = lambda query: geolocator.geocode("%s, Houston, TX" % query)

geolocator = Nominatim(user_agent="team5")
location = geolocator.geocode("1931 Santa Rosa 77023")

print((location.latitude, location.longitude))
print(location.address)

The result of above is:

(30.8757886, -87.2426917) 1931, Brownsdale Loop Road, Santa Rosa County, Florida, 32565, United States


Solution

  • When you call location = geolocator.geocode("1931 Santa Rosa 77023") you are overriding your query assignment at the top

    geolocator = Nominatim(user_agent="team5")
    geocode = lambda query: geolocator.geocode("%s, Houston, TX" % query)
    print(geocode("1931 Santa Rosa 77023")) # CUSTOM QUERY
    print(geolocator.geocode("1931 Santa Rosa 77023")) # WITHOUT CUSTOM QUERY
    

    See the difference in output

    None
    1931, Brownsdale Loop Road, Santa Rosa County, Florida, 32565, United States
    

    Note however that you can always run

    print(geolocator.geocode("1931 Santa Rosa 77023", exactly_one=False))
    

    to get a list of all available locations for a given address, and in this case it seems like the Florida one is the only one that matches your query string

    This is confirmed if you run a manual search yourself using openmaps