fetch_places.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import requests
  2. import json
  3. import pygeohash as pgh
  4. from google.cloud import firestore
  5. import os
  6. os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "physigo-firebase-adminsdk-uneji-b592d0d14b.json"
  7. db = firestore.Client()
  8. batch = db.batch()
  9. count = 0
  10. overpass_url = "https://overpass-api.de/api/interpreter"
  11. with open('map features.txt', 'r') as f:
  12. for line in f:
  13. if line[0] == "#":
  14. continue
  15. category, category_name = line.split(":")
  16. category_name = category_name.replace("\"", "").strip()
  17. overpass_query = f"""
  18. [out:json];
  19. area["ISO3166-1"="PL"][admin_level=2];
  20. node[{category}](area);
  21. out center;
  22. """
  23. response = requests.get(overpass_url, params={"data": overpass_query})
  24. try:
  25. elements = response.json()["elements"]
  26. except json.JSONDecodeError:
  27. print(f"Could not decode data for {category}")
  28. continue
  29. object_type = category.split("=")[1].strip()
  30. data = {}
  31. for el in elements:
  32. try:
  33. data["name"] = el["tags"].get("name", category_name)
  34. data["location"] = {
  35. "geohash": pgh.encode(el["lat"], el["lon"], precision=9),
  36. "geopoint": firestore.GeoPoint(el["lat"], el["lon"])
  37. }
  38. data["category"] = object_type
  39. batch.set(db.collection("Places").document(str(el["id"])), data)
  40. count += 1
  41. if count == 500:
  42. count = 0
  43. batch.commit()
  44. except Exception as e:
  45. print(e)
  46. continue
  47. batch.commit()
  48. count = 0
  49. print(f"Finished adding {line[:-1]}")