class OpenCageApi(object): def __init__(self, api_key): self.geolocator = OpenCage(api_key=api_key) def get_location_information(self, lat, long): location = self.geolocator.reverse(query=(lat, long)) return { 'country': location.raw.get('components').get('country'), 'continent': location.raw.get('components').get('continent') }
def get_location(query, format, api_key): """Get geographic data of a lab in a coherent way for all labs.""" # Play nice with the API... sleep(1) geolocator = OpenCage(api_key=api_key, timeout=10) # Variables for storing the data data = { "city": None, "address_1": None, "postal_code": None, "country": None, "county": None, "state": None, "country_code": None, "latitude": None, "longitude": None, "continent": None } road = "" number = "" # Default None values location_data = { "city": None, "road": None, "house_number": None, "postcode": None, "country": None, "county": None, "state": None, "ISO_3166-1_alpha-2": None, "country_code": None, "lat": None, "lng": None } # Reverse geocoding ... from coordinates to address if format == "reverse": # If the query (coordinates) is not empty if query is None or len(query) < 3: pass else: location = geolocator.reverse(query) if location is not None: location_data = location[0].raw[u'components'] location_data["lat"] = location[0].raw[u'geometry']["lat"] location_data["lng"] = location[0].raw[u'geometry']["lng"] # Direct geocoding ... from address to coordinates and full address if format == "direct": # If the query (address) is not empty if query is None or len(query) < 3: pass else: location = geolocator.geocode(query) if location is not None: location_data = location.raw[u'components'] location_data["lat"] = location.raw[u'geometry']["lat"] location_data["lng"] = location.raw[u'geometry']["lng"] # Extract the meaningful data for component in location_data: if component == "town" or component == "city": data["city"] = location_data[component] if component == "road": road = location_data[component] if component == "house_number": number = location_data[component] if component == "postcode": data["postal_code"] = location_data[component] if component == "country": data["country"] = location_data[component] if component == "county": data["county"] = location_data[component] if component == "state": data["state"] = location_data[component] if component == "ISO_3166-1_alpha-2": data["country_code"] = location_data[component] # The address need to be reconstructed data["address_1"] = unicode(road) + " " + unicode(number) data["latitude"] = location_data["lat"] data["longitude"] = location_data["lng"] # Format the country code to three letters try: data["country_code"] = pycountry.countries.get( alpha_2=data["country_code"]).alpha_3 except: data["country_code"] = None # Get the continent try: continent_code = pycountry.country_alpha2_to_continent_code( data["country_code"]) data["continent"] = pycountry.convert_continent_code_to_continent_name( continent_code) except: data["continent"] = None # Return the final data return data
#print(len(coords)) if (len(coords) == 0): coords.append([latlon[0], latlon[1], 0]) # Uses the geopy geolocator to convert coordinates into addresses, # ignores points in the middle of nowhere # makes multiple attempts in the case of a timeout found = False attempt = 0 nattempts = 5 #print(rt) if (cont == True): print(len(coords)) while not found and attempt < nattempts: try: location = geolocator.reverse(latlon) found = True except geopy.exc.GeocoderTimedOut: attempt += 1 print('Geocoder timed out %i times...') location = None if location == None: continue else: address = location[0].address coords[-1][2] = address if address == 'Null Island' or address == 0: continue print(address)
# Try Nominatum last # To not overload OSM servers, they request a delay of atleast 1 second per request, add some extra time.sleep(2) address = nominatim_geolocator.reverse(point, exactly_one=True) provider = "Nominatim" with open("Nominatim.json", "a") as output: json.dump(address.raw, output, sort_keys=True, indent=4) output.write(",\n") response = nominatim_parser(address.raw, longitude, latitude) response[0].execute() except: try: print("OpenCage") # Try OpenCage first time.sleep(2) address = opencage_geolocator.reverse(point, exactly_one=True) provider = "OpenCage" with open("OpenCage.json", "a") as output: json.dump(address.raw, output, sort_keys=True, indent=4) output.write(",\n") response = opencage_parser(address.raw, longitude, latitude) response[0].execute() except GeocoderQuotaExceeded or GeocoderTimedOut or GeocoderServiceError: print("Could not access geocoders for location: " + point_string) break # Skips if cannot find locat if len(location_bulk_insert_queries) != 0: Locations.insert_many(location_bulk_insert_queries).execute() print("Inserted " + str(len(location_bulk_insert_queries)) + " Records") else: with open(os.path.join(rootdir, "Location History.json"), 'r') as source: data = json.load(source)
# Try Nominatum last # To not overload OSM servers, they request a delay of atleast 1 second per request, add some extra time.sleep(2) address = nominatim_geolocator.reverse(point, exactly_one=True) provider = "Nominatim" with open("Nominatim.json", "a") as output: json.dump(address.raw, output, sort_keys=True, indent=4) output.write(",\n") response = nominatim_parser(address.raw, longitude, latitude) response[0].execute() except: try: print("OpenCage") # Try OpenCage first time.sleep(2) address = opencage_geolocator.reverse(point, exactly_one=True) provider = "OpenCage" with open("OpenCage.json", "a") as output: json.dump(address.raw, output, sort_keys=True, indent=4) output.write(",\n") response = opencage_parser(address.raw, longitude, latitude) response[0].execute() except GeocoderQuotaExceeded or GeocoderTimedOut or GeocoderServiceError: print("Could not access geocoders for location: " + point_string) break # Skips if cannot find locat if len(location_bulk_insert_queries) != 0: Locations.insert_many(location_bulk_insert_queries).execute() print("Inserted " + str(len(location_bulk_insert_queries)) + " Records") else: with open(os.path.join(rootdir, "LocationHistory.json"), 'r') as source: data = json.load(source)