Извлечение ключей геометрии / местоположения из Google API JSON в Python 3: AttributeError: у объекта «list» нет атрибута «read» - PullRequest
0 голосов
/ 30 марта 2019

Я геокодирую с JSON в качестве вывода, а затем хочу извлечь геометрию: ключи местоположения для хранения lat | Информация для последующей визуализации. Я получаю сообщение об ошибке

AttributeError: у объекта 'list' нет атрибута 'read'

Я не нашел ответа о переполнении стека или сайте simplejson. Я был бы признателен за руководство по ошибкам в моем синтаксисе. Спасибо! PS. Я удалил ключ API Google, чтобы избежать $$. Надеюсь, у вас есть одна возможность, если вы захотите запустить код и таким образом идентифицировать ошибку.

import googlemaps

импорт pprint

import simplejson as json

с даты и времени импорта, даты и времени

gmaps = googlemaps.Client (ключ = 'вставить ключ API Google')

Геокодирование адреса

geocode_result = gmaps.geocode ('1600 Amphitheatre Parkway, Mountain View, CA')

pprint.pprint (geocode_result)

* +1025 * python_conversion = json.load (geocode_result.read ())

geo_input = json.dumps ([s ['geometry'] ['location'] для s в python_conversion ['address_components']], отступ = 3)

pprint.pprint (geo_input)

Первая часть кода возвращает этот JSON:

[{'address_components': [{'long_name': '1600', 'short_name': '1600', 'types': ['street_number']}, {'long_name': 'Амфитеатр Паркуэй', 'short_name': 'Амфитеатр Pkwy', 'types': ['route']}, {'long_name': 'Mountain View', 'short_name': 'Mountain View', 'types': ['locality', 'политические']}, {'long_name': 'Округ Санта-Клара', 'short_name': 'Округ Санта-Клара', 'types': ['administrator_area_level_2', 'Политическое']}, {'long_name': 'California', 'short_name': 'CA', 'types': ['administrator_area_level_1', 'Политическое']}, {'long_name': 'United States', 'short_name': 'US', «типы»: [«страна», «политическая»]}, {'long_name': '94043', 'short_name': '94043', 'types': ['postal_code']}], 'formatted_address': '1600 Амфитеатр Pkwy, Маунтин-Вью, Калифорния 94043, США', 'geometry': {'location': {'lat': 37.4217407, 'lng': -122.0832867}, 'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lat': 37.4230896802915, 'lng': -122.0819377197085}, 'юго-запад': {'широта': 37.4203917197085, 'lng': -122.0846356802915}}}, 'place_id': 'ChIJhehRjJ-5j4ARKFssUSrwnhY', 'плюс_код': {'составной_код': 'CWC8 + RP Mountain View, Калифорния, Юнайтед' 'Состояния', 'global_code': '849VCWC8 + RP'}, 'types': ['street_address']}]

Во второй части, где я извлекаю географические координаты, я получаю указанную ошибку.

1 Ответ

0 голосов
/ 25 апреля 2019

Вот что я делаю для Google Адресов:

from googleplaces import GooglePlaces, types, lang
YOUR_API_KEY = 'Get an API key from google'


google_places = GooglePlaces(YOUR_API_KEY)

query_result = google_places.nearby_search(
        location='Manhattan', keyword='Coffee')#,
        #radius=200000)#, types=[types.TYPE_HEALTH])

if query_result.has_attributions:
    print (query_result.html_attributions)

station_names=[]
station_locs=[]
station_ids=[]
ct=0
for place in query_result.places:
    # Returned places from a query are place summaries.
    station_names.append(place.name)
    ct+=1
    station_locs.append(place.geo_location)
    station_ids.append(place.place_id)

    # The following method has to make a further API call.
    place.get_details()
    # Referencing any of the attributes below, prior to making a call to
    # get_details() will raise a googleplaces.GooglePlacesAttributeError.
    #print (place.details) # A dict matching the JSON response from Google.
    #print (place.local_phone_number)
    #print (place.international_phone_number)
    #print (place.website)
    #print (place.url)


#ct=0
# Are there any additional pages of results?
while( query_result.has_next_page_token and ct<200):
    ct+=1
    query_result_next_page = google_places.nearby_search(
            pagetoken=query_result.next_page_token)
    print("more pages")
    for place in query_result_next_page.places:
        station_names.append(place.name)
        station_locs.append(place.geo_location)

station_tuples=[]
for p in station_locs:
    station_tuples.append((float(p['lat']),float(p['lng'])))
...