0

I am new to python, and as usual, I am running to some trouble. I am trying to store the result of api.geocode(place) to the list location using a loop, but the loop stops when no match for the place is found. Here is a minimal example.

from gmaps import Geocoding
api = Geocoding(api_key = 'API Key')
address = ["Philippines", "Canada", "No place like this, Australia", "Malaysia"]
location = []
for place in address:
    location.append(api.geocode(place))

This throws this error:

Traceback (most recent call last):

  File "<ipython-input-54-8a375b31e18c>", line 2, in <module>
    location.append(api.geocode(place))

  File "/home/quack/anaconda3/lib/python3.6/site-packages/gmaps/geocoding.py", line 37, in geocode
    return self._make_request(self.GEOCODE_URL, parameters, "results")

  File "/home/quack/anaconda3/lib/python3.6/site-packages/gmaps/client.py", line 89, in _make_request
    )(response)

NoResults: {'results': [], 'status': 'ZERO_RESULTS', 'url': 'https://maps.googleapis.com/maps/api/geocode/json?address=No+place+like+this%2C+Australia&sensor=false&key=AIzaSyA-lk2z3VIZuKAq27ooswFPqjIKUDlMC2M'}

I tried to use a try and except solution like the following:

for place in address:
    try:
        location.append(api.geocode(place))
    except:
        pass

This results to a list location of length 3. How would I indicate NoResult in place of the result for No place like this, Australia and continue with the loop?

2 Answers 2

2

if I understand your question correctly:

from gmaps import Geocoding
api = Geocoding(api_key = 'API Key')
address = ["Philippines", "Canada", "No place like this, Australia", "Malaysia"]
location = []
for place in address:
    try:
        location.append(api.geocode(place))
    except Exception as e:
        location.append("No Result")

but a better approach would be :

from gmaps import Geocoding
api = Geocoding(api_key = 'API Key')
address = ["Philippines", "Canada", "No place like this, Australia", "Malaysia"]
location = {}
for place in address:
    try:
        location[place] = api.geocode(place)
    except Exception as e:
        location[place] = "No Result"

build a dictionary where u can see which places do not exist.

Sign up to request clarification or add additional context in comments.

Comments

1

You can add the raised NoResults exception to your location list.

for place in address:
    try:
        location.append(api.geocode(place))
    except Exception as exc:
        location.append(exc)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.