Example #1
0
    def __init__(self, coordinates, distance, direction=None):
        self.coordinates = coordinates
        self.distance = distance
        self.direction = self.get_direction(direction)
        self.direction_degrees = self.DIRECTIONS.get(
            direction.lower() if direction else self.DEFAULT_DIRECTION)
        self.radius = self.distance / (2 * math.pi) * self.CORRELATION_FACTOR

        self.gmaps = Client(app.config['GOOGLE_MAPS_API_KEY'])  # geoCoding
        self.dirs = Client(app.config['GOOGLE_MAPS_API_KEY'])  # directions
        logger.debug(' Initialize request with coordinates {} '.format(
            self.coordinates))
def extractFeatures(deliveries, api_key):		

	#calculates tip
	deliveries['tip'] = deliveries['paid'] - deliveries['total']

	#calculates tipPercent
	deliveries['tipPercent'] = deliveries['tip'] / deliveries['total']

	#converts date to datetime obj and adds date/time features to df
	dates = pd.to_datetime(deliveries['date'] + '-' + 
		deliveries['time'], format='%Y-%m-%d-%H:%M')	
	deliveries['dayofyear'] = dates.dt.dayofyear
	deliveries['dayofmonth'] = dates.dt.day
	deliveries['dayofweek'] = dates.dt.weekday
	deliveries['month'] = dates.dt.month
	deliveries['hour'] = dates.dt.hour.apply(lambda time: 24 if time == 0 else time)

	
	#get API key
	gmapskey = Client(key=api_key)
	#applies geocode function to get lat and long
	deliveries['latitude'], deliveries['longitude'] = zip(
		*deliveries['address'].apply(extractCoords, kwargs=(api_key,)))
	
	#gets zip code from address
	deliveries['zip'] = deliveries['address'].apply(
		lambda address: int(address.split()[-1]))

	return deliveries
Example #3
0
 def get_lat_long(self, location):
     gmaps = Client(key='AIzaSyADU4JlRIaly445PDXwCpBUs8Mq5tZsndo')
     geocode_result = gmaps.geocode(location)
     lat_long = {}
     lat_long["latitude"] = geocode_result[0]['geometry']['location']['lat']
     lat_long["longitude"] = geocode_result[0]['geometry']['location']['lng']
     return lat_long
def geocode_addresses(df):
    """Geocode addresses in a dataframe."""
    try:
        initialize_app()
    except ValueError:
        pass
    api_key = get_google_maps_api_key()
    gmaps = Client(key=api_key)
    for index, item in df.iterrows():
        # FIXME: Handle existing lat and long more elegantly.
        # try:
        #     if item.latitude and item.longitude:
        #         continue
        # except:
        #     pass
        address = f"{item.street}, {item.city}, {item.state} {item.zip}"
        geocode_result = gmaps.geocode(address)
        if geocode_result:
            df.at[index, "formatted_address"] = geocode_result[0]["formatted_address"]
            location = geocode_result[0]["geometry"]["location"]
            print(item.name, "-->", location)
            df.at[index, "latitude"] = location["lat"]
            df.at[index, "longitude"] = location["lng"]
            # TODO: Round latitude and longitude (4-6 decimal places?)
            for info in geocode_result[0]["address_components"]:
                key = info["types"][0]
                if key == "administrative_area_level_2":
                    df.at[index, "county"] = info["long_name"]

        sleep(2)  # Prevents spamming Google's servers (necessary?)
    return df
Example #5
0
def index(request):

    google_key = settings.GOOGLE_API
    geocode_url = settings.GEOCODE_URL
    gmaps = Client(key=google_key)

    profile_instance = Profile.objects.get(id=request.user.id)
    hood_instance = Hood.objects.filter(hood_name=profile_instance.profile_hood.hood_name)

    place = profile_instance.profile_hood.hood_location.loc_name

    place = place.strip().replace(" ", "+")
    response = requests.get(geocode_url.format(place, google_key))

    general_address = response.json()
    address = general_address['results'][0]['geometry']['location']


    nearby_police_results = gmaps.places_nearby(location=address, keyword='police',
                                                language='en-US', open_now=True,
                                                rank_by='distance', type='police')

    nearby_hospital_results = gmaps.places_nearby(location=address, keyword='hospital',
                                                  language='en-US', open_now=True,
                                                  rank_by='distance', type='hospital')


    hood_news = News.objects.filter(news_hood=hood_instance)

    return render(request, 'index.html', {'hood_news': hood_news,  'police': nearby_police_results, 'hospitals': nearby_hospital_results})
Example #6
0
def get_place_details(
    query: str,
    api_key: Optional[str] = None,
    fields: Optional[List[str]] = None,
):
    """Get the place details for a given a name.
    Args:
        query (str): The text to use to search for a place.
        api_key (str): Optional Google Maps API key, None by default.
        fields (list): Optional fields to retrieve.
    Returns:
        (dict): A dictionary of place details.
    """
    if api_key is None:
        api_key = get_google_maps_api_key()
    if not fields:
        fields = [
            'formatted_address',
            'photo',
            'opening_hours',
            'website',
        ]
    gmaps = Client(key=api_key)
    search = places.find_place(gmaps, query, 'textquery')
    place_id = search['candidates'][0]['place_id']
    place = places.place(gmaps, place_id, fields=fields)
    return place['result']
Example #7
0
def get_place_details(place_id):
        """ Returns a dict of - website, opening hours and maps url of the given place_id  """

        google_client = Client(app.config['GOOGLE_API_KEY'])
        
        result = places.place(google_client, place_id, fields=['url', 'website', 'opening_hours'])
        return result['result']
def distance_list(origin, destination):
    try:
        origin = "NTU+" + origin + "+Singapore"
        pass
    except:
        pass
    for i in range(len(destination)):
        try:
            destination[i] = "NTU+" + destination[i].replace(
                " ", "+") + "+Singapore"
        except:
            pass

    gmaps = Client(key=API_KEY)
    matrix = gmaps.distance_matrix(origin, destination, mode="walking")
    list = []
    for i in range(len(matrix['rows'][0]['elements'])):
        if matrix['rows'][0]['elements'][i][
                'status'] == 'ZERO_RESULTS':  # Check for infeasible routes
            list.append(
                None
            )  # If there is no viable routes, distance is returned as None
        else:
            list.append(
                int(
                    float(matrix['rows'][0]['elements'][i]['distance']['text']
                          [:len(matrix['rows'][0]['elements'][i]['distance']
                                ['text']) - 3]) * 1000))
    return list
Example #9
0
def get_transit_times(origin, destination):
    key = application.config['GOOGLE_MAPS']
    c = Client(key)
    d = c.directions(origin, destination, mode='transit', alternatives=True)

    results = set()
    for route in d:
        duration = route['legs'][0]['duration']['text']
        steps = route['legs'][0]['steps']
        transit_details = [x for x in steps if x.get('travel_mode') == 'TRANSIT'][0]['transit_details']
        depart_stop = transit_details['departure_stop']['name']
        depart_stop = depart_stop.replace('Subway', '')
        depart_stop = depart_stop.replace('Station', '')
        depart_stop = depart_stop.replace('Atlantic Avenue', '')
        line = transit_details['line']['short_name']
        try:
            icon = transit_details['line']['icon']
        except KeyError:
            icon = transit_details['line']['vehicle']['icon']

        status, text = morning.get_line_status(line)
        icon_html = '<img src="{}">'.format(icon)
        # results.add((line, depart_stop, duration, icon, status, text))
        results.add((icon_html, depart_stop, duration, status, text))
    return sorted(list(results), key=lambda x: x[2])
Example #10
0
 def get_lat_long(self):
     gmaps = Client(key=settings.GMAPS_API_KEY)
     results = gmaps.geocode(address=self.address + ", " + self.city,
                             region="CA")
     if results:
         lat_lng = results[0]['geometry']['location']
         return lat_lng
Example #11
0
def find_traffic(hours, minutes):
    addresses = []
    gmaps = Client('AIzaSyCaQlauoQ1njrABzhVCliY49DaByZNYkTY')
    cassie_work = '3237 S 16th St, Milwaukee, WI 53215'
    joey_work = '1550 Innovation Way, Hartford, WI 53027'
    with open('address.txt') as f:
        addresses = f.readlines()
    file = open('times.csv', 'a')
    day = datetime.datetime.today().weekday()
    for addr_newline in addresses:
        addr = addr_newline.rstrip()
        directions_cassie = None
        directions_joey = None
        if (hours < 8):
            directions_cassie = gmaps.directions(addr, cassie_work)
            directions_joey = gmaps.directions(addr, joey_work)
        else:
            directions_cassie = gmaps.directions(cassie_work, addr)
            directions_joey = gmaps.directions(joey_work, addr)
        file.write(
            str(addr) + ',' + format_time(hours, minutes) + ',Cassie,' +
            str(directions_cassie[0]['legs'][0]['duration']['value']) +
            ',Joey,' +
            str(directions_joey[0]['legs'][0]['duration']['value']) + ',' +
            str(day) + '\n')
    file.close()
Example #12
0
def geocode_addresses(df, api_key: Optional[str] = None):
    """Geocode addresses in a dataframe.
    Args:
        df (DataFrame): A DataFrame containing the addresses to geocode.
    Returns:
        (DataFrame): Returns the DataFrame with geocoded latitudes and longitudes.
    """
    if api_key is None:
        api_key = get_google_maps_api_key()
    gmaps = Client(key=api_key)
    for index, item in df.iterrows():
        # TODO: Handle existing lat and long more elegantly.
        # try:
        #     if item.latitude and item.longitude:
        #         continue
        # except:
        #     pass
        address = f'{item.street}, {item.city}, {item.state} {item.zip}'
        geocode_result = gmaps.geocode(address)
        if geocode_result:
            df.at[index,
                  'formatted_address'] = geocode_result[0]['formatted_address']
            location = geocode_result[0]['geometry']['location']
            print(item.name, '-->', location)
            df.at[index, 'latitude'] = location['lat']
            df.at[index, 'longitude'] = location['lng']
            # TODO: Round latitude and longitude (4-6 decimal places?)
            for info in geocode_result[0]['address_components']:
                key = info['types'][0]
                if key == 'administrative_area_level_2':
                    df.at[index, 'county'] = info['long_name']

        sleep(.2)  # Prevents spamming Google's servers (necessary?).
    return df
Example #13
0
def run(cities: list) -> list:
    """
    Main run function. Obtains client with API key and creates/returns
    distance_data file depending on whether the file exists

    :rtype: list
    :param cities: list
    :return: upper triangular matrix of distances
    """
    client = Client(key=dotenv.get('API_KEY'))
    try:
        is_empty = os.stat('distance_data').st_size == 0
        if is_empty:
            with open('distance_data', mode='wb') as data_file:
                matrix = iter_gather(client, cities)
                pickle.dump(matrix, data_file)
                return matrix
        else:
            with open('distance_data', mode='r+b') as data_file:
                matrix = pickle.load(data_file)
                if len(matrix) != len(cities):
                    matrix = iter_gather(client, cities)
                    file_bytes = pickle.dumps(matrix)
                    data_file.seek(0)
                    data_file.write(file_bytes)
                    data_file.truncate()
                return matrix
    except FileNotFoundError:
        with open('distance_data', mode='ab') as data_file:
            matrix = iter_gather(client, cities)
            pickle.dump(matrix, data_file)
            return matrix
def convert_geocoding(lat, lng):
    gm = Client(key=API_KEY)
    revGeo = gm.reverse_geocode(
        (lat, lng)
    )  # reverse_geocode func in googlemaps return 	list of reverse geocoding results
    return revGeo[0][
        "formatted_address"]  # retrieve information from the list returned
def search_for_address(query, api_key=None, fields=["formatted_address"]):
    """Search for the address of a given name."""
    if api_key is None:
        api_key = get_google_maps_api_key()
    gmaps = Client(key=api_key)
    place = places.find_place(gmaps, query, "textquery", fields=fields)
    return place["candidates"]
Example #16
0
def findLat(addr):
    # Function to find latitude and longitude using google maps API
    gmaps = Client(key='AIzaSyAr6MafwMH3Anrx_aJNb3_y7KrWKlCcNOA')
    geocode_result = gmaps.geocode(addr)
    lat = geocode_result[0]["geometry"]["location"]["lat"]
    lon = geocode_result[0]["geometry"]["location"]["lng"]
    return [lat, lon]
Example #17
0
def geocode_addresses(df, api_key):
    """Geocode addresses in a dataframe given that the dataframe has fields:
         - street
         - city
         - state
         - zip
    A 1 second pause is applied between requests to honor Google's usage limits.
    https://developers.google.com/maps/documentation/javascript/usage-and-billing#other-usage-limits
    """
    gmaps = Client(key=api_key)
    for index, item in df.iterrows():
        address = f'{item.street}, {item.city}, {item.state} {item.zip}'
        geocode_result = gmaps.geocode(address)
        sleep(1)
        if geocode_result:
            location = geocode_result[0]['geometry']['location']
            formatted_address = geocode_result[0]['formatted_address']
            df.at[index, 'formatted_address'] = formatted_address
            df.at[index, 'latitude'] = location['lat']
            df.at[index, 'longitude'] = location['lng']
            for info in geocode_result[0]['address_components']:
                key = info['types'][0]
                if key == 'administrative_area_level_2':
                    df.at[index, 'county'] = info['long_name']
        else:
            print('Failed to geocode:', index)
    return df
Example #18
0
def query_google(company_name, google_apikey, country_codes=None, additional_keywords=None):
    additional_keywords = ['plant'] if additional_keywords is None else additional_keywords
    google_maps = Client(key=google_apikey)

    if country_codes is None:
        raise Exception("""
        List of ISO 3166-1 alpha-2 country codes required, e.g. country_code_list=['DE']. 
        See https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 for codes.""")

    all_res = []

    for cc in country_codes:
        country_res = google_maps.places(' '.join([company_name] + additional_keywords), region=cc).get('results')
        if country_res:
            all_res += [r for r in country_res if
                        any(
                            [company_name.lower() in r.get(f, '').lower() for f in ['formatted_address', 'name']]) and
                        not any(
                            [term in r.get('formatted_address', '').lower() for term in
                                [f'near {company_name}', f'behind {company_name}']])]

    all_res = [r for r in all_res if not any([tag in r['types'] for tag in ['car_dealer', 'car_repair', 'store']])]

    addresses = pd.DataFrame([[d['name'],
                               d['formatted_address'],
                               d['geometry']['location']['lat'],
                               d['geometry']['location']['lng']]
                               for d in all_res], columns=['name', 'address', 'lat', 'lng'])

    addresses = addresses.assign(
        source='places_apis'
    )

    return addresses
Example #19
0
def coordinate_encoder(address):
    gmaps = Client(key="XXXXXXXXXX")
    coordinates = gmaps.geocode(address)[0]['geometry']['location']
    coords_lat = str(coordinates["lat"])
    coords_lng = str(coordinates["lng"])
    coords_total = coords_lat + "," + coords_lng
    return coords_total
Example #20
0
    def get_CA_census(self, postcode, city, location, ip):
        gmaps = Client(key=settings.GOOGLE_GEOCODE_KEY)
        results = gmaps.reverse_geocode(
            (location['latitude'], location['longitude']))

        for r in results[0]['address_components']:
            try:
                types = r['types']
                if types[0] == 'locality' and types[1] == 'political':
                    city = r['long_name']
                    if city == 'Mississauga':
                        city = 'Toronto'

                if types[0] == 'postal_code':
                    postcode = r['long_name']
            except:
                pass

        # first try from IPStore, else lookup census database and update the
        #  ipstore in the process
        census, ipstore = self.get_from_ipstore(ip, postcode)

        if not census:
            census = CaCensus(city=city).get_profile()
            ipstore.census = census
            ipstore.geocode = results
            ipstore.geocoded_postal_code = postcode
            ipstore.save()
            # IPStore.objects.create(
            #     ip=ip,
            #     census=census,
            #     geocode=results,
            #     geocoded_postal_code=postcode
            # )
        return census
Example #21
0
    def set_google_maps_fields(self, latlng=None, calls=True):
        """
        Uses the Google Maps API to set:
          - geocoded latlng
          - nearest school name + distance
          - nearest train station name + distance
        """
        client = Client(key=settings.GOOGLE_MAPS_API_SERVER_KEY)
        if not latlng:
            data = client.geocode(self.address)
            if not data:
                raise Exception("Unable to resolve the address: '%s'" % address)
            latlng = data[0]["geometry"]["location"]
        self.point = GEOSGeometry("POINT(%(lng)s %(lat)s)" % latlng)

        if (calls):
            error = ""
            for field in ("school", "train_station"):
                try:
                    place = client.places_nearby(location=latlng, rank_by="distance", type=field)["results"][0]
                except IndexError:
                    continue
                except Exception as e:
                    error = e
                    continue
                setattr(self, "nearest_%s" % field, place["name"])
                place_latlng = place["geometry"]["location"]
                d = distance((latlng["lat"], latlng["lng"]), (place_latlng["lat"], place_latlng["lng"])).km
                setattr(self, "nearest_%s_distance" % field, round(d, 2))
            if error:
                raise Exception(error)
Example #22
0
def gmaps_parser(start_point="Feuerbergstrasse 6, Hamburg",
                 end_point="Bundesstrasse 53, Hamburg",
                 mode="bicycling"):
    """
    Obtain the track using the google maps api
    """
    from googlemaps import Client
    api_key = os.environ['MAPS_API_KEY']
    gmaps = Client(api_key)
    directions = gmaps.directions(start_point, end_point, mode=mode)

    lat_bike = np.array([
        step['start_location']['lat']
        for step in directions[0]['legs'][0]['steps']
    ])
    lon_bike = np.array([
        step['start_location']['lng']
        for step in directions[0]['legs'][0]['steps']
    ])
    time = np.array([
        step['duration']['value'] for step in directions[0]['legs'][0]['steps']
    ])
    dtime_bike = np.cumsum(pd.to_timedelta(time, unit='s'))

    return lon_bike, lat_bike, dtime_bike
Example #23
0
def main():
    # Initialize the API object
    gmaps = Client(api_key_maps)
    route_map = Client(api_key_route)

    # origin = raw_input('Where are you starting? (please enter a valid address) ')
    # dest = raw_input('Where are you going? (please enter a valid address) ')
    origin = 'Ogunquit, ME'
    dest = 'Coral Gables, FL'

    lat0, lng0 = gmaps.geocode(origin)[0]['geometry']['location'].values()
    print 'start: ', lat0, lng0

    lat1, lng1 = gmaps.geocode(dest)[0]['geometry']['location'].values()
    print 'end: ', lat1, lng1

    routes = route_map.directions(origin, dest)

    lats = []
    longs = []
    times = []

    for i, step in enumerate(routes[0]['legs'][0]['steps']):
        lats.append(step['start_location']['lat'])
        longs.append(step['start_location']['lng'])
        if i == len(routes[0]['legs'][0]['steps']) - 1:
            lats.append(step['end_location']['lat'])
            longs.append(step['end_location']['lng'])

        times.append(step['duration']['value'])

    new_times = [sum(times[:i]) for i in range(len(times) + 1)]
    travel_route = zip(lats, longs)
    markers = fifteen_mile_markers(zip(lats, longs))

    # Dan - Test
    # print markers
    print[i[2] for i in segment_times(travel_route, new_times, markers)]

    gmap_plt = gmplot.GoogleMapPlotter((lat0 + lat1) / 2.0,
                                       (lng0 + lng1) / 2.0, 16)

    gmap_plt.plot([i[0] for i in markers], [i[0] for i in markers], 'r')
    gmap_plt.plot(lats, longs)
    gmap_plt.plot([mark[0] for mark in markers], [mark[1] for mark in markers])
    gmap_plt.draw("mymap.html")
    return
def obtain_commute_times(origin, destination, time_range):
    '''
    This function will obtain the commute times from origin to destination 
    '''
    from googlemaps import Client
    from datetime import datetime, timedelta
    import numpy as np
    import time

    API_key = 'AIzaSyCJUNcLHEBBi8pd2CyYzSzlFZFvb_vOhaU'
    gmaps = Client(API_key)

    # The time interval on x-axis between each api call/data point
    time_interval = 600  # Seconds, or 10 minutes
    t_int_minutes = time_interval / 60

    # This gives the nearest wednesday at midnight to the current data
    today = datetime.today()
    today_ind = today.weekday()
    day_modif = 16 - today_ind  # 16 to get the nearest wednesday, two weeks from now
    wednesday_mid = today + timedelta(days=day_modif,
                                      seconds=-today.second,
                                      minutes=-today.minute,
                                      hours=-today.hour)
    print(wednesday_mid)
    wed_mid_int = int(wednesday_mid.strftime("%s"))

    # This converts the start time into an integer time on monday
    hour_range_depart = time_range

    # This builds your time array based on the start time and end time monday

    start_time = wed_mid_int + hour_range_depart[0] * 3600
    end_time = wed_mid_int + hour_range_depart[1] * 3600
    time_interval = int((end_time - start_time) / time_interval)

    # Use linspace to make our integer times
    times = np.linspace(start_time, end_time, time_interval + 1,
                        endpoint=True).astype(np.int)

    org = origin
    dest = destination

    org_mat = [org]
    dest_mat = [dest]

    commute_times = [] * len(times)

    for i in range(0, len(times)):
        dept_time_iter = times[i]
        directions = gmaps.distance_matrix(org_mat,
                                           dest_mat,
                                           departure_time=dept_time_iter,
                                           traffic_model='pessimistic')
        commute_time = directions['rows'][0]['elements'][0][
            'duration_in_traffic']['value']
        commute_times.append(commute_time)

    return commute_times
Example #25
0
def select(paras):
    a = time.time()
    gmaps = Client(key='AIzaSyAdtMHxfsESr0OuVdGuseM_VW_uiDtahJY')
    address = paras['street'] + ", " + paras['city'] + ", " + paras['state']
    latitude, longtitude = geofind(address)
    print "Location convertion: " + str(latitude) + str(longtitude)
    time_start_mon = int(paras['s_mon'])
    time_start_day = int(paras['s_day'])
    time_start_hour = int(paras['s_hou'])
    time_end_mon = int(paras['e_mon'])
    time_end_day = int(paras['e_day'])
    time_end_hour = int(paras['e_hou'])
    radius = paras['r']
    start_time = datetime.datetime(YEAR, time_start_mon, time_start_day,
                                   time_start_hour, 0)
    end_time = datetime.datetime(YEAR, time_end_mon, time_end_day,
                                 time_end_hour, 0)
    start_epoch_time = time.mktime(start_time.timetuple()) * 1000
    print "start" + str(start_epoch_time)
    end_epoch_time = time.mktime(end_time.timetuple()) * 1000
    distance = "3959*acos((sin({3}/57.29577951)*sin(latitude/57.29577951)+cos({3}/57.29577951)*cos(latitude/57.29577951)*cos(abs(longtitude-({2}))/57.29577951))) <{4}"
    querystr = (
        "select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} and "
        + distance + " order by user;").format(start_epoch_time,
                                               end_epoch_time, longtitude,
                                               latitude, radius)

    if (paras['r'] == '0'):
        querystr = (
            "select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} order by user;"
        ).format(start_epoch_time, end_epoch_time)
    print querystr
    con, cur = sql_execute(querystr)
    b = time.time()
    f = open('timestamp', 'w')
    f.write(str(b - a))
    f.close()
    data = []
    while True:
        dat = cur.fetchone()
        if dat == None:
            break
        data.append(dat)
    # print "paras['type']=" + paras['type'] # paras['type']=0
    if (paras['type'] == '0'):
        return top_k_similar(data, paras['option1'], paras['option2'],
                             paras['deadline'])
    if (paras['type'] == '1'):
        return mst.call_mst(data, paras['deadline'])
    if (paras['type'] == '2'):
        return kmeans_new.call_kmeans(data, paras['deadline'],
                                      int(paras['option1']))
    if (paras['type'] == '3'):
        return represent.call_represent(data, paras['deadline'],
                                        int(paras['option1']))
    else:
        return [], []
    pass
Example #26
0
def calculate_distance():
    """Calculate the distance for all apartments that were not calculated yet.

    - Query all pins;
    - Query all apartments not yet calculated;
    - Call Google Maps Distance Matrix;
    - Save the results.
    """
    maps = Client(key=read_from_keyring(PROJECT_NAME, 'google_maps_api_key'))
    assert maps
    tomorrow = date.today() + timedelta(0 if datetime.now().hour < 9 else 1)
    morning = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 9, 0)
    LOGGER.warning('Next morning: %s', morning)

    empty = dict(text='ERROR', value=-1)
    for pin in Pin.query.all():
        while True:
            apartments = Apartment.query.outerjoin(Distance, and_(
                Apartment.id == Distance.apartment_id, Distance.pin_id == pin.id)) \
                .filter(Apartment.active.is_(True), Distance.apartment_id.is_(None)).limit(20)
            search = {
                apartment.id: apartment.address
                for apartment in apartments.all()
            }
            if not search:
                LOGGER.warning('All distances already calculated for %s', pin)
                break

            ids = list(search.keys())
            origin_addresses = list(search.values())
            LOGGER.warning('Calling Google Maps for %s', pin)
            try:
                result = maps.distance_matrix(origin_addresses, [pin.address],
                                              mode='transit',
                                              units='metric',
                                              arrival_time=morning)
            except HTTPError as err:
                LOGGER.error('Error on Google Distance Matrix: %s', str(err))
                continue
            LOGGER.warning('Processing results from Google Maps for %s', pin)
            for row_dict in [row['elements'][0] for row in result['rows']]:
                duration, distance = row_dict.get('duration',
                                                  empty), row_dict.get(
                                                      'distance', empty)
                meters = distance.get('value')
                apt_id = ids.pop(0)
                model = Distance.create(apartment_id=apt_id,
                                        pin_id=pin.id,
                                        json=row_dict,
                                        meters=meters,
                                        minutes=round(
                                            duration.get('value') / 60))
                if meters <= 0:
                    LOGGER.error('Error calculating %s: %s', model,
                                 json.dumps(row_dict))
                else:
                    LOGGER.warning('Calculating %s', model)
Example #27
0
def cota(latitude, longitude):
    gmaps = Client(key=KEY)
    aux = 1
    cotas = []
    entrada = []
    while aux < len(latitude):
        if (aux % 6 == 0 and aux != 0):
            entrada.append(
                str(latitude[aux - 1]) + ',' + str(longitude[aux - 1]))
            url = entrada[0] + entrada[1] + entrada[2] + entrada[3] + entrada[
                4] + entrada[5]
            a = gmaps.elevation(url)
            print(round(100 * aux / (entradas.limite - entradas.inicio), 2),
                  '% ')
            for i in range(0, 6):
                cotas.append(float(a[i].get('elevation')))
            del (entrada[:])
            del (a)
        else:
            entrada.append(
                str(latitude[aux - 1]) + ',' + str(longitude[aux - 1]) + '|')
        aux += 1

    if len(latitude) == 1:
        entrada.append(str(latitude[aux - 1]) + ',' + str(longitude[aux - 1]))
        url = entrada
        a = gmaps.elevation(url)
        cotas.append(float(a[0].get('elevation')))
        del (entrada[:])
        del (a)

    if len(entrada):

        entrada.append(
            str(latitude[aux - 1]) + ',' + str(longitude[aux - 1]) + '|')
        url = entrada[0]
        aux5 = 0
        while aux5 + 1 < len(entrada):
            url = url + entrada[aux5 + 1]
            aux5 += 1
        url = url[0:len(url) - 1]
        a = gmaps.elevation(url)
        print(round(100 * aux / (entradas.limite - entradas.inicio), 2), '% ')
        aux2 = 0
        while len(a):
            cotas.append(float(a[aux2].get('elevation')))
            aux2 += 1
            aux += 1
            if aux2 == len(a):
                break

    print(
        round(
            100 * (entradas.limite - entradas.inicio) /
            (entradas.limite - entradas.inicio), 2), '% ')

    return cotas
Example #28
0
def is_valid_config_entry(opp, logger, api_key, origin, destination):
    """Return whether the config entry data is valid."""
    origin = resolve_location(opp, logger, origin)
    destination = resolve_location(opp, logger, destination)
    client = Client(api_key, timeout=10)
    try:
        distance_matrix(client, origin, destination, mode="driving")
    except ApiError:
        return False
    return True
 def __init__(self, connection_string=None):
     self.client = Client(get_api_key())
     self.connection_string = connection_string
     self.engine = create_engine(connection_string)
     self.Session = sessionmaker(bind=self.engine)
     self.session = self.Session()
     self.from_addresses = []
     self.to_addresses = []
     self.results = []
     Base.metadata.create_all(bind=self.engine)
Example #30
0
def is_valid_config_entry(hass, api_key, origin, destination):
    """Return whether the config entry data is valid."""
    origin = find_coordinates(hass, origin)
    destination = find_coordinates(hass, destination)
    client = Client(api_key, timeout=10)
    try:
        distance_matrix(client, origin, destination, mode="driving")
    except ApiError:
        return False
    return True