cget
cget

Reputation: 410

Python / Google Maps API - TimeoutError: [Errno 60] Operation timed out when calling a function from the terminal

I'm calling a function from my terminal, which connects to the Google Maps API to return the coordinates of a place.

However, I'm getting this error

sock.connect((self.host, self.port))
TimeoutError: [Errno 60] Operation timed out

The process is as follows:

>>>> python
>>>> from geocode import getGeocodeLocation
>>>> getGeocodeLocation("New York")

Error:

sock.connect((self.host, self.port))
TimeoutError: [Errno 60] Operation timed out

The code I'm using is as follows geocode.py - I don't think there a problem with this as it ran fine before.

import httplib2
import json

def getGeocodeLocation(inputString):
    # Use Google Maps to convert a location into Latitute/Longitute coordinates

    google_api_key = "my_api_key"
    locationString = inputString.replace(" ", "+")
    url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (locationString, google_api_key))
    h = httplib2.Http()
    result = json.loads(h.request(url,'GET')[1])
    latitude = result['results'][0]['geometry']['location']['lat']
    longitude = result['results'][0]['geometry']['location']['lng']
    return (latitude,longitude)

Any ideas what might be wrong?

Upvotes: 1

Views: 1116

Answers (2)

Glenn
Glenn

Reputation: 1

the issue with your local internet environment with your code editor, if you paste the request URL with the API key, the response is normal. but in the local, request from your local code. it will not work, I solved it with the wire guard mode of my VPN, a similar situation is discussed here as well I have just discovered that my new ISP is blocking outbound connection on port 445.

Upvotes: 0

evan
evan

Reputation: 5701

I get (40.7127753, -74.0059728) as output when I run your exact code (with my own key) on RStudio Cloud. So this is likely an API key-related, environment-related or network-related issue.

To narrow down the issue I recommend you try it out on the same platform. These is how I set it up:

geocode.py

import httplib2
import json

def getGeocodeLocation(inputString):
    # Use Google Maps to convert a location into Latitute/Longitute coordinates

    google_api_key = "MY_API_KEY"
    locationString = inputString.replace(" ", "+")
    url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (locationString, google_api_key))
    h = httplib2.Http()
    result = json.loads(h.request(url,'GET')[1])
    latitude = result['results'][0]['geometry']['location']['lat']
    longitude = result['results'][0]['geometry']['location']['lng']
    return (latitude,longitude)

main.py

from geocode import getGeocodeLocation
getGeocodeLocation("New York")

Also make sure that your API key is valid and that you have billing and Geocoding API enabled on your project. Refer to Google's get started guide.

Hope this helps you!

Upvotes: 1

Related Questions