2

以下のコードを試していますが、うまくいきません。

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

このコードを実行しようとすると、エラーが発生します。問題を解決するために私を助けてください。

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
4

2 に答える 2

0

取得しているエラーについてここでいくつかのことを読むと、応答が適切に返されるのに十分なヘッダーが要求に渡されていないことが原因である可能性があることがわかります。

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

GoogleMapsパッケージのソースを見るfetch_jsonと、 headers パラメータなしで呼び出されていることがわかります:

...
    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

ここにfetch_json関数があるので、headersパラメーターが空のように見える{}ので、おそらくそれが問題です:

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))

パッケージのソースをコピーして、GoogleMapsパッチを当てることができます。

于 2013-10-05T12:33:30.803 に答える