def get_location_from_address(address): geolocator = OpenCage(api_key=settings.OPENCAGE_API_KEY) location = geolocator.geocode(address) if location.latitude and location.longitude: return (location.latitude, location.longitude) else: return None
def geolocation(): from geopy.geocoders import OpenCage geolocator = OpenCage('d1d1fbc618ef41b89d3ebde37f53d1b2') for p in Province.query.all(): g = geolocator.geocode(p.name + ", Việt Nam", timeout=60) p.latitude = g.latitude p.longitude = g.longitude print((p.latitude, p.longitude)) db.session.commit()
def __init__(self, name): self.city = name if self.city not in City.CITIES: #OpenCage Geocoder geolocator = OpenCage(api_key=KEY) location = geolocator.geocode(self.city, timeout=6) if location is None: raise TypeError('city does not exist') self.latitude = location.latitude self.longitude = location.longitude City.CITIES[self.city] = (location.latitude, location.longitude) else: self.latitude = City.CITIES[self.city][0] self.longitude = City.CITIES[self.city][1]
def make_main_figure(year, address): if year is None: raise PreventUpdate if address is None: raise PreventUpdate # process address input by user, get latitude and longitude if address not in ADDRESS_CACHE: api_key = opencage_key geolocator = OpenCage(api_key, domain='api.opencagedata.com', scheme=None, user_agent='AQMap', format_string=None, timeout=4) ADDRESS_CACHE[address] = geolocator.geocode(address) location = ADDRESS_CACHE[address] user_lat = location.latitude user_lon = location.longitude # get necessary dataframes from PostGIS database ozone_df = qd.get_pollutant_annual_df(year, 'ozone', location.latitude, location.longitude) ozone_geo_df = qd.get_pollutant_annual_avg_df(year, 'ozone', location.latitude, location.longitude, 10) pm25_df = qd.get_pollutant_annual_df(year, 'pm25', location.latitude, location.longitude) pm25_geo_df = qd.get_pollutant_annual_avg_df(year, 'pm25', location.latitude, location.longitude, 10) no2_df = qd.get_pollutant_annual_df(year, 'no2', location.latitude, location.longitude) no2_geo_df = qd.get_pollutant_annual_avg_df(year, 'no2', location.latitude, location.longitude, 10) temp_df = qd.get_temp_annual_df(year, location.latitude, location.longitude) temp_geo_df = qd.get_temp_annual_avg_df(year, location.latitude, location.longitude, 10) # making the ozone geo plots ozonefig = make_scatter(ozone_df, 'slateblue', 'Month', 'Concentration (ppm)', 'Ozone', 'month', 'conc') ozonegeo = make_geo_mapbox(ozone_geo_df, 'Mean Annual Ozone', 'st_x', 'st_y', 'conc', user_lon, user_lat) # making the pm2.5 plots pm25fig = make_scatter(pm25_df, 'seagreen', 'Month', 'Concentration (μg/m^3)', 'PM2.5','month','conc') pm25geo = make_geo_mapbox(pm25_geo_df, 'Mean Annual PM2.5', 'st_x', 'st_y', 'conc', user_lon, user_lat) # making the no2 plots no2fig = make_scatter(no2_df, 'goldenrod', 'Month', 'Concentration (ppb)', 'Nitrogen Dioxide','month','conc') no2geo = make_geo_mapbox(no2_geo_df, 'Mean Annual Nitrogen Dioxide', 'st_x', 'st_y', 'conc', user_lon, user_lat) # making the temp plots tempfig = make_scatter(temp_df, 'tomato', 'Month', '˚C', 'Maximum Temperature', 'month', 'tmax') tempgeo = make_geo_mapbox(temp_geo_df, 'Mean Annual Temperature', 'st_x', 'st_y', 'tmax', user_lon, user_lat) return tempfig, tempgeo, ozonefig, ozonegeo, pm25fig, pm25geo, no2fig, no2geo
def index(): client = MongoClient() db = client.health_data form = AddressForm(request.form) if request.method == 'POST': """ Find closest bike station to given address """ collection = db.bike_stations addr = request.form.get("address") geolocator = OpenCage('d79317ac2c4be89c2683778d8a95df49', timeout=None) location = geolocator.geocode(addr) compass = findLocation( location.latitude, location.longitude) closestBikeStation = compass.nearby(compass.coordinates, collection) """ Switch to finding closest corner store (farmer's market will be added later) to bike station """ compass = findLocation( closestBikeStation['geometry']['coordinates'][1], closestBikeStation['geometry']['coordinates'][0] ) collection = db.healthy_corner_stores closestHealthyStore = compass.nearby(compass.coordinates, collection) """ Farmer's market """ collection = db.farmers_markets closestFarmersMarket = compass.nearby(compass.coordinates, collection) """ Bike path's """ collection = db.bike_network closestBikePath = compass.nearby(compass.coordinates, collection) """ Mapp generation""" currentMapp = Mapp(location.latitude, location.longitude, closestBikeStation['geometry']['coordinates'], closestHealthyStore['geometry']['coordinates'], addr, closestBikeStation, closestHealthyStore, closestFarmersMarket,closestBikePath) currentMapp.generateMapp() """ Return new page with found values plugged into template """ return render_template("result.html", bikestation=closestBikeStation['properties']['addressStreet'], market=closestHealthyStore['properties']['OFFICIAL_STORE_NAME'], farmersmarket=closestFarmersMarket['properties']['NAME']) else: return render_template("index.html", form=form)
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
from geopy.geocoders import OpenCage key = 'd1d1fbc618ef41b89d3ebde37f53d1b2' provincesList = ['An Giang','Bà Rịa - Vũng Tàu','Bạc Liêu','Bắc Kạn','Bắc Giang','Bắc Ninh','Bến Tre','Bình Dương','Bình Định','Bình Phước','Bình Thuận','Cà Mau','Cao Bằng','Cần Thơ','Đà Nẵng','Đắk Lắk','Đắk Nông','Đồng Nai','Đồng Tháp','Điện Biên','Gia Lai','Hà Giang','Hà Nam','Hà Nội','Hà Tĩnh','Hải Dương','Hải Phòng','Hòa Bình','Hậu Giang','Hưng Yên','Thành phố Hồ Chí Minh','Khánh Hòa','Kiên Giang','Kon Tum','Lai Châu','Lào Cai','Lạng Sơn','Lâm Đồng','Long An','Nam Định','Nghệ An','Ninh Bình','Ninh Thuận','Phú Thọ','Phú Yên','Quảng Bình','Quảng Nam','Quảng Ngãi','Quảng Ninh','Quảng Trị','Sóc Trăng','Sơn La','Tây Ninh','Thái Bình','Thái Nguyên','Thanh Hóa','Thừa Thiên - Huế','Tiền Giang','Trà Vinh','Tuyên Quang','Vĩnh Long','Vĩnh Phúc','Yên Bái'] coodinatesList = [] geolocator = OpenCage(key) for p in provincesList: g = geolocator.geocode( p + ", Việt Nam", timeout=60) coodinatesList.append((g.latitude, g.longitude)) print(coodinatesList)
class GeoSearch: def __init__(self, dao=None): self.geolocator_nominatim = None self.geolocator_google = None self.geolocator_opencage = None self.geolocator_bing = None self.dao = dao def search_nominatim(self, address): try: self.geolocator_nominatim = Nominatim(proxies={'http': self.get_proxy()}) location = self.geolocator_nominatim.geocode(address, timeout=20) if location: lat = location.latitude lon = location.longitude full_address = location.address if 40.485808 < lat < 40.917691 and -73.699206 > lon > -74.260380: return lat, lon, full_address else: return None, None else: return None, None except (GeocoderTimedOut, AttributeError): return None, None def search_google(self, address): try: self.geolocator_google = GoogleV3(api_key='AIzaSyAwv1G4XIza' '5IIlwucRjWZlFA3lbynGG_8', proxies={'http': self.get_proxy()}) location = self.geolocator_google.geocode(address, timeout=20) if location: lat = location.latitude lon = location.longitude full_address = location.address if 40.485808 < lat < 40.917691 and -73.699206 > lon > -74.260380: return lat, lon, full_address else: return None, None else: return None, None except (GeocoderTimedOut, AttributeError): return None, None def search_opencage(self, address): try: self.geolocator_opencage = OpenCage(api_key='d65ff98d8e33b1b85210ed4a400fc3a1', proxies={'http': self.get_proxy()}) location = self.geolocator_opencage.geocode(address, timeout=20) if location: lat = location.latitude lon = location.longitude full_address = location.address if 40.485808 < lat < 40.917691 and -73.699206 > lon > -74.260380: return lat, lon, full_address else: return None, None else: return None, None except (GeocoderTimedOut, AttributeError): return None, None def search_bing(self, address): try: self.geolocator_bing = Bing(api_key='AuqD7e7LRzuD5Wzmn2HqTQPIipUyZrbgz2y_' 'efTS9YtGhio37GkJr9IWmnRV4EOB', proxies={'http': self.get_proxy()}) location = self.geolocator_bing.geocode(address, timeout=20) if location: lat = location.latitude lon = location.longitude full_address = location.address if 40.485808 < lat < 40.917691 and -73.699206 > lon > -74.260380: return lat, lon, full_address else: return None, None else: return None, None except (GeocoderTimedOut, AttributeError): return None, None def search_dao(self, address, borough): results = self.dao.do("SELECT ST_X(geomout), ST_Y(geomout), " "(addy).zip FROM geocode('" + address + "') As g LIMIT 1;") return self.verify_address(address, results, borough) @staticmethod def verify_address(adress, results, borough): zips = Normalizer.select_zipcode_class(Normalizer.get_neighborhood(borough)) for r in results: zip3dig = int(r[2]) / 100 if zip3dig in zips: return r[0], r[1], adress+", "+r[2] return None def get_proxy(self): proxies = ['durianproxy.gq', 'proxyrocket.org', 'apricotproxy.gq', 'technoproxy.cf', 'mawoop.ml', 'proxyfree.party', 'accessproxy.org', 'proxyeuro.pw', 'zqal.xyz', 'bukus.ga', 'popeyeprox.info', 'b2bproxy.cf', 'buzy.ml', 'limeproxy.gq', 'web.proxygogo.info', 'broccoliproxy.gq', 'xyzproxy.gq', 'franceproxy.pw', 'ispvpn.com' ] return proxies[randint(0, len(proxies) - 1)]