lib.py 1.6 KB

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