lib.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import json
  2. import math
  3. import requests
  4. import haversine
  5. # Google API key, with access to Street View Static API
  6. google_api_key = "AIzaSyAqjCYR6Szph0X0H_iD6O1HenFhL9jySOo"
  7. metadata_url = "https://maps.googleapis.com/maps/api/streetview/metadata"
  8. mapcrunch_url = "http://www.mapcrunch.com/_r/"
  9. def generate_coord():
  10. """
  11. Returns (latitude, longitude) of usable coord (where google has data).
  12. Returns None if, after trying several random points, no usable coords could be found.
  13. This function calls the streetview metadata endpoint - there is no quota consumed
  14. """
  15. points_res = requests.get(mapcrunch_url).text
  16. points_js = json.loads(points_res.strip("while(1); "))
  17. for lat, lng in points_js["points"]:
  18. params = {
  19. "key": google_api_key,
  20. "location": f"{lat},{lng}",
  21. }
  22. js = requests.get(metadata_url, params=params).json()
  23. if js["status"] != "ZERO_RESULTS":
  24. return (lat, lng)
  25. mean_earth_radius_km = (6378 + 6357) / 2
  26. # the farthest you can be from another point on Earth
  27. antipode_dist_km = math.pi * mean_earth_radius_km
  28. min_dist_km = 0.15 # if you're within 150m, you get a perfect score
  29. # if you're more than 1/4 of the Earth away, you get 0
  30. max_dist_km = antipode_dist_km / 2
  31. perfect_score = 5000
  32. def score(target, guess):
  33. """
  34. Takes in two (latitude, longitude) pairs and produces an int score.
  35. Score is in the (inclusive) range [0, 5000]
  36. Higher scores are closer.
  37. """
  38. dist_km = haversine.haversine(target, guess)
  39. if dist_km <= min_dist_km:
  40. return perfect_score
  41. if dist_km >= max_dist_km:
  42. return 0
  43. # TODO probably still needs tweaking
  44. return int(perfect_score * (1 - (dist_km / max_dist_km) ** 2))