goks
goks

Reputation: 1206

403 Error while geocoding with GoogleMaps

I am trying with below code and it is not working.

from googlemaps import GoogleMaps
gmaps = GoogleMaps(api_key='mykey')
reverse = gmaps.reverse_geocode(38.887563, -77.019929)
address = reverse['Placemark'][0]['address']
print(address)

when i try to run this code i am getting below errors. Please help me in resolving the issue.

Traceback (most recent call last):
  File "C:/Users/Gokul/PycharmProjects/work/zipcode.py", line 3, in <module>
    reverse = gmaps.reverse_geocode(38.887563, -77.019929)
  File "C:\Python27\lib\site-packages\googlemaps.py", line 295, in reverse_geocode
    return self.geocode("%f,%f" % (lat, lng), sensor=sensor, oe=oe, ll=ll, spn=spn, gl=gl)
  File "C:\Python27\lib\site-packages\googlemaps.py", line 259, in geocode
    url, response = fetch_json(self._GEOCODE_QUERY_URL, params=params)
  File "C:\Python27\lib\site-packages\googlemaps.py", line 50, in fetch_json
    response = urllib2.urlopen(request)
  File "C:\Python27\lib\urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 410, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

Upvotes: 2

Views: 1822

Answers (2)

user2375821
user2375821

Reputation:

Reading the book "Foundation of Python Network Programming", written in 2010, I found myself dealing with a similar error. Sligthly changing the code samples, I got to this error message:

The Geocoding API v2 has been turned down on September 9th, 2013. The Geocoding API v3 should be used now. Learn more at https://developers.google.com/maps/documentation/geocoding/

Aparently, the params needed in the url and the url itself changed. Used to be:

params = {'q': '27 de Abril 1000, Cordoba, Argentina',
          'output': 'json', 'oe': 'utf8'}
url = 'http://maps.google.com/maps/geo?' + urllib.urlencode(params)

And is now:

params = {'address': '27 de Abril 1000, Cordoba, Argentina',                    
          'sensor': 'false'}                                                   

url = 'http://maps.googleapis.com/maps/api/geocode/json?' + urllib.urlencode(params)

I asume googlemaps python package hasn't updated yet.

This worked for me.

Below a full example, what more or less must be what GoogleMap() is doing behind the scenes:

import urllib, urllib2                                                          
import json                                                                     

params = {'address': '27 de Abril 1000, Cordoba, Argentina',                    
          'sensor': 'false'}                                                   

url = 'http://maps.googleapis.com/maps/api/geocode/json?' + urllib.urlencode(params)

rawreply = urllib2.urlopen(url).read()                                          
reply = json.loads(rawreply)                                                    

lat = reply['results'][0]['geometry']['location']['lat']                        
lng = reply['results'][0]['geometry']['location']['lng']                        

print '[%f; %f]' % (lat, lng)

Upvotes: 2

Emil Davtyan
Emil Davtyan

Reputation: 14089

Reading some stuff here about the error you are getting, shows that it maybe caused by the fact that the request is not being passed enough headers for the response to comeback properly.

https://stackoverflow.com/a/13303773/220710

Looking at the source of the GoogleMaps package, you can see that fetch_json is being called without a headers parameter :

...
    url, response = fetch_json(self._GEOCODE_QUERY_URL, params=params)
    status_code = response['Status']['code']
    if status_code != STATUS_OK:
        raise GoogleMapsError(status_code, url, response)
    return response

Here is the fetch_json function, so it seems the headers parameter is an empty {} so maybe that is the issue :

def fetch_json(query_url, params={}, headers={}):       # pylint: disable-msg=W0102
    """Retrieve a JSON object from a (parameterized) URL.

    :param query_url: The base URL to query
    :type query_url: string
    :param params: Dictionary mapping (string) query parameters to values
    :type params: dict
    :param headers: Dictionary giving (string) HTTP headers and values
    :type headers: dict 
    :return: A `(url, json_obj)` tuple, where `url` is the final,
    parameterized, encoded URL fetched, and `json_obj` is the data 
    fetched from that URL as a JSON-format object. 
    :rtype: (string, dict or array)

    """
    encoded_params = urllib.urlencode(params)    
    url = query_url + encoded_params
    request = urllib2.Request(url, headers=headers)
    response = urllib2.urlopen(request)
    return (url, json.load(response))

You could copy the source of the GoogleMaps package and attempt to patch it.

Upvotes: 0

Related Questions