import json import requests from config import FSQ_API_KEY from dbstore.peewee_store import create_or_update_poi POI_API_ENDPOINT = "https://api.foursquare.com/v3/places/nearby?ll={}%2C{}&limit=10" POI_DETAIL_ENDPOINT = "https://api.foursquare.com/v3/places/{}" POI_SEARCH_API_ENDPOINT = "https://api.foursquare.com/v3/places/search?query={}&ll={}%2C{}&radius=2000&limit=10" POI_PHOTO_ENDPOINT = "https://api.foursquare.com/v3/places/{}/photos?sort=POPULAR&limit=10" OSM_ENDPOINT = "https://www.openstreetmap.org/?mlat={}&mlon={}&zoom=15&layers=M" headers = { "accept": "application/json", "Authorization": FSQ_API_KEY } def query_poi(search, latitude, longitude): locations = list() url = POI_SEARCH_API_ENDPOINT.format(search, latitude, longitude) response = requests.get(url, headers=headers) for poi in json.loads(response.text)["results"]: loc = { "fsq_id": poi["fsq_id"], "name": poi["name"], "locality": poi["location"]["locality"] if "locality" in poi["location"] else "", "region": poi["location"]["region"] if "region" in poi["location"] else "", "latitude": poi["geocodes"]["main"]["latitude"], "longitude": poi["geocodes"]["main"]["longitude"], "osm_url": OSM_ENDPOINT.format(poi["geocodes"]["main"]["latitude"], poi["geocodes"]["main"]["longitude"]) } locations.append(loc) create_or_update_poi(loc) return locations def query_poi_by_fsq_id(fsq_id): url = POI_DETAIL_ENDPOINT.format(fsq_id) response = requests.get(url, headers=headers) poi = json.loads(response.text) loc = { "fsq_id": fsq_id, "name": poi["name"], "locality": poi["location"]["locality"] if "locality" in poi["location"] else "", "region": poi["location"]["region"] if "region" in poi["location"] else "", "latitude": poi["geocodes"]["main"]["latitude"], "longitude": poi["geocodes"]["main"]["longitude"], "osm_url": OSM_ENDPOINT.format(poi["geocodes"]["main"]["latitude"], poi["geocodes"]["main"]["longitude"]) } create_or_update_poi(loc) return loc def get_poi_top_photo(fsq_id): url = POI_PHOTO_ENDPOINT.format(fsq_id) response = requests.get(url, headers=headers) poi_photo_urls = [] for poi in json.loads(response.text): prefix = poi["prefix"] suffix = poi["suffix"] poi_photo_urls.append(prefix + "original" + suffix) if len(poi_photo_urls) == 0: return None return poi_photo_urls[0]