0

I am trying to call Google Map API from Python 3.8.

import urllib
import json

serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'

while True:
    address = input('Enter location: ')
    if len(address) < 1:
        break

    url = serviceurl + urllib.urlencode({'sensor': 'false',
                                         'address': address})
    print('Retrieving', url)
    uh = urllib.urlopen(url)
    data = uh.read()
    print('Retrieved', len(data), 'characters')

    try:
        js = json.loads(str(data))
    except:
        js = None
    if 'status' not in js or js['status'] != 'OK':
        print('==== Failure To Retrieve ====')
        print(data)
        continue

    print(json.dumps(js, indent=4))

    lat = js["results"][0]["geometry"]["location"]["lat"]
    lng = js["results"][0]["geometry"]["location"]["lng"]
    print('lat', lat, 'lng', lng)
    location = js['results'][0]['formatted_address']
    print(location)

The compilation error is at urllib.urlencode and at urllib.urlopen..

And it is

Cannot find reference 'urlencode' in 'init_.pyi'

evan
  • 5,443
  • 2
  • 11
  • 20
Ajesh
  • 59
  • 1
  • 1
  • 5

1 Answers1

0

There are several issues in your code. First of all, urllib has been split up in Python 3, please check out 'module' has no attribute 'urlencode'.

Secondly, you need to use the HTTPS protocol in the Geocoding request, and make sure that you use a valid API key:

serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?key=AIza****sYjs&'

Thirdly, replace json.loads(str(data)) with just json.loads(data).

Full amended code below:

import urllib.parse
import urllib.request
import json

serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?key=AIza****sYjs&'

while True:
    address = input('Enter location: ')
    if len(address) < 1:
        break

    url = serviceurl + urllib.parse.urlencode({'sensor': 'false',
                                               'address': address})
    print('Retrieving', url)
    uh = urllib.request.urlopen(url)
    data = uh.read()
    print('Retrieved', len(data), 'characters')
    try:
        js = json.loads(data)
    except:
        js = None
    if 'status' not in js or js['status'] != 'OK':
        print('==== Failure To Retrieve ====')
        print(data)
        continue

    print(json.dumps(js, indent=4))

    lat = js["results"][0]["geometry"]["location"]["lat"]
    lng = js["results"][0]["geometry"]["location"]["lng"]
    print('lat', lat, 'lng', lng)
    location = js['results'][0]['formatted_address']
    print(location)

Output for e.g. "paris,france":

Enter location: paris,france
Retrieving https://maps.googleapis.com/maps/api/geocode/json?key=AIza****sYjs&sensor=false&address=paris%2Cfrance
Retrieved 1690 characters
{
    "results": [
        {
            "address_components": [
                {
                    "long_name": "Paris",
                    "short_name": "Paris",
                    "types": [
                        "locality",
                        "political"
                    ]
                },
                {
                    "long_name": "Paris",
                    "short_name": "Paris",
                    "types": [
                        "administrative_area_level_2",
                        "political"
                    ]
                },
                {
                    "long_name": "\u00cele-de-France",
                    "short_name": "IDF",
                    "types": [
                        "administrative_area_level_1",
                        "political"
                    ]
                },
                {
                    "long_name": "France",
                    "short_name": "FR",
                    "types": [
                        "country",
                        "political"
                    ]
                }
            ],
            "formatted_address": "Paris, France",
            "geometry": {
                "bounds": {
                    "northeast": {
                        "lat": 48.9021449,
                        "lng": 2.4699208
                    },
                    "southwest": {
                        "lat": 48.815573,
                        "lng": 2.224199
                    }
                },
                "location": {
                    "lat": 48.856614,
                    "lng": 2.3522219
                },
                "location_type": "APPROXIMATE",
                "viewport": {
                    "northeast": {
                        "lat": 48.9021449,
                        "lng": 2.4699208
                    },
                    "southwest": {
                        "lat": 48.815573,
                        "lng": 2.224199
                    }
                }
            },
            "place_id": "ChIJD7fiBh9u5kcRYJSMaMOCCwQ",
            "types": [
                "locality",
                "political"
            ]
        }
    ],
    "status": "OK"
}
lat 48.856614 lng 2.3522219
Paris, France

Hope this helps!

evan
  • 5,443
  • 2
  • 11
  • 20
  • I did exactly as you said but i am getting a message.{ "error_message" : "The provided API key is invalid.", "results" : [], "status" : "REQUEST_DENIED" } – Ajesh Feb 02 '20 at 09:19
  • Of course. You need to replace "AIza****sYjs" with your own API key. I'm assuming that you have a valid API key that belongs to a project that has billing enabled and Geocoding API enabled. – evan Feb 03 '20 at 11:47
  • So how will I get a valid API key? I need to purchase it from google maps?? – Ajesh Feb 09 '20 at 05:10
  • I recommend you follow Google's get started guide https://developers.google.com/maps/gmp-get-started – evan Feb 09 '20 at 10:07