Skip to content

Instantly share code, notes, and snippets.

@jerlendds
Created March 13, 2021 23:43
Show Gist options
  • Save jerlendds/bfde9368fccedaa381673675f48e7176 to your computer and use it in GitHub Desktop.
Save jerlendds/bfde9368fccedaa381673675f48e7176 to your computer and use it in GitHub Desktop.
import requests
class PlacesAutocomplete:
"""https://developers.google.com/maps/documentation/places/web-service/autocomplete?hl=id
Args:
components (str) : expects country code e.g. country:ca
place_types (str) : e.g. (cities)
key (str) : Google Places autocomplete API key
"""
_request_error = {"status": "failed"}
def __init__(self, components, place_types, key):
self.components = components
self.place_types = place_types
self.key = key
def _fetch_raw_response(self, search_text):
try:
if "&" in search_text:
raise ValueError
except ValueError:
return PlacesAutocomplete._request_error
url = f"https://maps.googleapis.com/maps/api/place/autocomplete/json?input={search_text}&components={self.components}&types={self.place_types}&key={self.key}"
try:
response = requests.get(url)
response = response.json()
except ConnectionError:
return PlacesAutocomplete._request_error
try:
response_status = response.get("status")
response_predictions = response.get("predictions")
except KeyError:
return PlacesAutocomplete._request_error
if response_status == "OK" and response_status != "ZERO_RESULTS":
# Limiting the amount of returned predictions to 4
if len(response_predictions) > 4:
reduced_suggestions = response_predictions[:4]
response["predictions"] = reduced_suggestions
return response
return response
return {"status": response.get("status")}
def fetch_suggestion_hints(self, search_text):
suggestions = []
location_hints = self._fetch_raw_response(search_text)
if location_hints["status"] != "OK":
return PlacesAutocomplete._request_error
else:
for suggestion in location_hints["predictions"]:
suggestions.append(suggestion["description"])
return suggestions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment