Esempio n. 1
0
def avoidRoute(lon, lat, lon2, lat2, profile):
    buffer = []
    #Seting the route coordinates
    coordinates = [[lon, lat], [lon2, lat2]]
    #Open Route Service credentials
    api_key = '5b3ce3597851110001cf62480bce1c9f6f5041d0ae79d1a8847f8b98'
    clnt = client.Client(key=api_key)
    #Makes a request to get the traffic information
    get_feature_collection = "http://127.0.0.1:5000/traffic-information"
    feature_collection_req = requests.get(url=get_feature_collection)
    feature_collection = feature_collection_req.json()
    #Adding buffers
    for geom in feature_collection['features']:
        route_buffer = LineString(geom['geometry']['coordinates']).buffer(
            0.0005)  # Create geometry buffer
        simp_geom = route_buffer.simplify(0.00005)  # Simplify geometry
        buffer.append(simp_geom)
    #Merging the buffer geometries in case there are 2 or more polygons next to each other
    union_buffer = cascaded_union(buffer)

    avoid_request = {
        'coordinates': coordinates,
        'format_out': 'geojson',
        'profile': profile,
        'preference': 'shortest',
        'instructions': False,
        'options': {
            'avoid_polygons': mapping(union_buffer)
        }
    }
    avoid_route = clnt.directions(**avoid_request)

    return avoid_route
Esempio n. 2
0
def calc_distance_matrix(marker_coords):
    ors_clnt = client.Client(key=app.config['ORS_KEY'])

    request = {'locations': marker_coords,
           'profile': 'foot-walking',
           'metrics': ['duration']}
    
    dist_matrix = ors_clnt.distance_matrix(**request)
    return dist_matrix
Esempio n. 3
0
def get_distance_matrix_response(marker_coords):
    ors_clnt = client.Client(key=get_instance_settings().ors_key)

    request = {
        'locations': marker_coords,
        'profile': 'foot-walking',
        'metrics': ['duration']
    }

    dist_matrix_response = ors_clnt.distance_matrix(**request)
    return dist_matrix_response
Esempio n. 4
0
    def __init__(self, GoogleAPIKey=None, OpenAPIKey=None, prefferedDistanceMatrix="Open"):
        self.GoogleAPIKey = GoogleAPIKey       
        self.OpenAPIKey = OpenAPIKey
        self.GoogleClient = gclient(key=self.GoogleAPIKey)
        self.OpenRouteClient = orclient.Client(key=self.OpenAPIKey)

        if prefferedDistanceMatrix != "Open" and prefferedDistanceMatrix != "Google":
            raise ValueError("prefferedDistanceMatrix should be \"Open\" or \"Google\"")
        elif prefferedDistanceMatrix == "Open":
            self.DistanceMatrix = self.__OpenDistanceMatrix
        elif prefferedDistanceMatrix == "Google":
            self.DistanceMatrix = self.__GoogleDistanceMatrix
Esempio n. 5
0
def directions_route_duration(route_coords):
    ors_clnt = client.Client(key=app.config['ORS_KEY'])
    request = {'coordinates': route_coords,
               'profile': 'foot-walking',
               'geometry': 'true',
               'format_out': 'geojson',
              }

    route = ors_clnt.directions(**request)
    # duration in minutes
    duration = route['features'][0]['properties']['summary'][0]['duration'] / 60

    return route, duration
    def iso_request(self, amenities, city_border):
        """Openrouteservice isochrone calculation"""

        print('Make sure to first build correct ORS graph! E.g. normal graph for normal isochrone request. \n'
              'Requesting isochrones...')

        # using local openrouteservice package with the manually created routing graph
        clnt = client.Client(base_url='http://localhost:8080/ors', key=self.api_key)

        # osm data id = id_1; hot data id = osm_id
        id_name = ['id_1' if 'id_1' in amenities else 'osm_id'][0]
        iso_range_values = SETTINGS['iso_range_values']
        request_counter = 0
        iso_df_list = []

        for geom, amenity_type, amenity_id in zip(amenities['geometry'], amenities['amenity'], amenities[id_name]):
            point_geom = mapping(geom)

            # isochrone parameters
            params_iso = {'locations': [[point_geom['coordinates'][0], point_geom['coordinates'][1]]],
                          'profile': 'driving-car',
                          'interval': iso_range_values[0],
                          'range': [iso_range_values[-1]]}

            try:
                # request isochrones
                iso_df = pd.DataFrame.from_dict(clnt.isochrones(**params_iso)['features'])
                # adjust geometry column for geopandas dataframe
                iso_df['geometry'] = [Polygon(g['coordinates'][0]) for g in iso_df['geometry']]
                # add additional data
                iso_df['value'] = [g['value'] for g in iso_df['properties']]
                iso_df['amenity'] = amenity_type
                iso_df['iso_id'] = request_counter
                iso_df['amenity_id'] = amenity_id
                iso_df_list.append(iso_df)

            except exceptions.ApiError:
                print(params_iso, 'is isolated and out of routing graph range.')
                pass
            request_counter += 1

        print('Requested isochrones for %s healthsite locations from ORS API' % request_counter)

        all_isochrones = pd.concat([layer for layer in iso_df_list])
        all_isochrones = gpd.GeoDataFrame(all_isochrones, geometry='geometry')

        return all_isochrones
Esempio n. 7
0
def requestRoute(lon, lat, lon2, lat2, profile):
    #Open Route Service credentials
    api_key = '5b3ce3597851110001cf62480bce1c9f6f5041d0ae79d1a8847f8b98'
    clnt = client.Client(key=api_key)
    #Seting the route coordinates
    coordinates = [[lon, lat], [lon2, lat2]]
    #Defines the route parameters
    direction_params = {
        'coordinates': coordinates,
        'profile': profile,
        'format_out': 'geojson',
        'preference': 'shortest',
        'instructions': False,
        'geometry': 'true'
    }
    #Makes a request to Open Route Service to get the route
    regular_route = clnt.directions(**direction_params)

    return regular_route
Esempio n. 8
0
def index():
    buffer = []
    api_key = '5b3ce3597851110001cf62480bce1c9f6f5041d0ae79d1a8847f8b98'  #https://openrouteservice.org/sign-up
    clnt = client.Client(key=api_key)
    map = folium.Map(
        tiles=
        'https://maps.heigit.org/openmapsurfer/tiles/roads/webmercator/{z}/{x}/{y}.png',
        attr=
        'Map data (c) OpenStreetMap, Tiles (c) <a href="https://heigit.org">GIScience Heidelberg</a>',
        location=([55.71459, 12.577]),
        zoom_start=7)  # Create map

    #Adding traffic information
    trafficUrl = "http://127.0.0.1:5000/traffic-information"
    req = requests.get(url=trafficUrl)
    traffic = req.json()

    #Styles the traffic information layer
    style_function = lambda x: {
        'color': 'red',
    }

    #Adds geoJson to the map
    folium.GeoJson(traffic, style_function=style_function).add_to(map)

    #Add route to the map
    routeUrl = "http://127.0.0.1:5000/request-route&start=12.624406814575197,55.664079718036724;&end=12.458496093750002,55.69422894298507;&profile=driving-car"
    routeReq = requests.get(url=routeUrl)
    route = routeReq.json()

    #Styles route
    style_route = lambda x: {
        'color': 'green',
    }
    map.add_child(folium.map.LayerControl())

    return map._repr_html_()
Esempio n. 9
0
import json
import folium
from openrouteservice import client, places, directions, distance_matrix
from geopy.geocoders import Nominatim
from statistics import median

# api key for openrouteservice (which will figure out the optimal route)
api_key = '5b3ce3597851110001cf62484c5ca3f76ff944dfa2d23b773efec8d7'
clnt = client.Client(key=api_key)

geolocator = Nominatim(user_agent='Meals On Wheels Route')

locs_addresses = [
    '64 pine street milford ma', '122 west spruce street milford ma',
    '8 della street milford ma', '14 lawrence street milford ma',
    '17 lawrence street milford ma', '59 lawrence street milford ma',
    '6 iadarola avenue milford ma', '36 highland street milford ma',
    '21 harding street milford ma', '8 western ave milford ma',
    '17 deluca rd milford ma', '3 prospect heights milford ma',
    '6 prospect heights milford ma', '34 prospect heights milford ma',
    ' 87 prospect heights milford ma'
]
locs_coords = []
latitudes = []
longitudes = []

# convert above addresses to coordinates using geopy
for loc in locs_addresses:
    curr = geolocator.geocode(loc)
    # print(curr.address)
    locs_coords.append((curr.longitude, curr.latitude))
Esempio n. 10
0
import json
import copy
import logging
import time

from openrouteservice import client
from itertools import groupby
import objectparams as opms
import transportmeans as trmns
import osm2geojson as o2g

logger = logging.getLogger('locationsearch')

opr_api_key = '' # put here your openrouteservice api key

opr_client = client.Client(key=opr_api_key)

timeout = 180

def process_request(payload):
    coords = payload['coords']
    main_object = payload['mainObject']
    relative_object = payload['relativeObject']

    poly_coords = None

    query = ""

    request_begin = time.time()

    # search considering time reach distance
Esempio n. 11
0
def update_map(n_clicks, add_start, add_end):
    if any([add_end is None, add_start is None]):
        pass

    else:
        # 1. Reverse-geocoding (i.e finding geo coordinates from addresses)
        geocod_start = geocoder.osm(add_start)
        geocod_end = geocoder.osm(add_end)

        # 2. Compute the box to look for POI around
        box = [(geocod_start.lat, geocod_end.lng),
               (geocod_end.lat, geocod_end.lng),
               (geocod_end.lat, geocod_start.lng),
               (geocod_start.lat, geocod_start.lng)]

        poly_box = Polygon(box)
        poly_box = poly_box.buffer(0.0025).simplify(0.05)

        # 3. Retrieve the POI in the area
        api = overpy.Overpass()
        result_nodes = api.query(
            "(node['shop']{0};node['amenity']{0};);out;".format(
                str(poly_box.exterior.bounds)))
        result_areas = api.query(
            "(area['shop']{0};area['amenity']{0};);out;".format(
                str(poly_box.exterior.bounds)))

        # 4. Filter the POI in the box to keep only the points to be avoid
        # Loading the csv for the danger levels
        dang_list = pd.read_csv(
            'C:/Users/daphn/Documents/EUvsVirus/hackathon_exchange/DangerScoreList.csv',
            delimiter=',')
        # Score the POI in the area
        nodes_score = add_score(
            dang_list, result_nodes
        )  # nodes_score is a list of overpy objects, with lat and lon info,

        dangers_poly = []  # sites_poly
        # I define dangerous a POI with score greater than 1
        for node in nodes_score:
            if node.tags['dangerscore'] != '1':
                lat = node.lat
                lon = node.lon

                dangers_poly_coords = Point(lon,
                                            lat).buffer(0.0002).simplify(0.05)
                dangers_poly.append(dangers_poly_coords)

        danger_buffer_poly = [
        ]  # site_buffer_poly, which is the input for the avoid polygon option
        for danger_poly in dangers_poly:
            poly = Polygon(danger_poly)
            danger_buffer_poly.append(poly)

        # 5.Request the route
        route_request = {
            'coordinates': [[geocod_start.lng, geocod_start.lat],
                            [geocod_end.lng, geocod_end.lat]],
            # Careful long then lat and not lat then long
            'format_out':
            'geojson',
            'profile':
            'foot-walking',
            'preference':
            'shortest',
            'instructions':
            False,
            'options': {
                'avoid_polygons': mapping(MultiPolygon(danger_buffer_poly))
            }
        }

        api_key = '5b3ce3597851110001cf6248d14c60f017174b11b170ff63fdbf48b3'
        clnt = client.Client(key=api_key)

        route_directions = clnt.directions(**route_request)

        # 6.Display the route and the dangerous points
        # Create the base map
        map = folium.Map(tiles='Stamen Toner',
                         location=([geocod_start.lat, geocod_start.lng]),
                         zoom_start=14)  # Create map

        # Beginning and end markers
        folium.Marker([geocod_start.lat, geocod_start.lng],
                      popup='<i>Start</i>').add_to(map)
        folium.Marker([geocod_end.lat, geocod_end.lng],
                      popup='<i>End</i>').add_to(map)

        # Plotting the dangerous areas
        folium.features.GeoJson(data=mapping(MultiPolygon(danger_buffer_poly)),
                                overlay=True).add_to(map)
        # Plotting the area of search
        folium.features.GeoJson(data=route_directions,
                                name='Route',
                                overlay=True).add_to(map)

        # Create the html
        updated_map_path = "C:/Users/daphn/Documents/EUvsVirus/visu/test.html"
        map.save(updated_map_path)

        return open(updated_map_path, 'r').read()
Esempio n. 12
0
('UBSF-20/24 PETECAS/CRIOULI', [-4.267368 , -41.758368, ubsf20, ttp20, ppp20])]

locais3 = ['Unidades Fechadas']

if hora in range(7, 11) and dia in range(0,5):
    locais = locais1   
elif hora in range(13, 16) and dia in range(0,5):
    locais = locais2
else:
  locais = locais3

#estilo da rota
style = {'color': '#fd2b85'}
# API do openroute services
api_key = '5b3ce3597851110001cf6248ce9c379b4c0446d6abf7ea0d29cd0da0'
clnt = client.Client(key=api_key) # Create client with api key

w = widgets.Dropdown(
    options= locais,
    description='UBSF:',
)
def on_change(change):
    if change['type'] == 'change' and change['name'] == 'value':
        clear_output(wait=True)
        display(w)
        valor = w.value
        print(valor)
        lat1 = valor[0]
        lon1 = valor[1]
        ubs = valor[2]
        mapa = folium.Map (location = [-4.275,-41.78],
        color=color,
        opacity=0.5,
        weight=4,
    )


# -

# ### Regular Route
#
# So far: The shortest route for a car from A to B.

# +
# Basic parameters
api_key = 'your_key'  # https://openrouteservice.org/sign-up
ors = client.Client(key=api_key)

map_berlin = folium.Map(
    tiles='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    attr=
    '&copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>',
    location=([52.516586, 13.381047]),
    zoom_start=13.5)  # Create map

popup_route = "<h4>{0} route</h4><hr>" \
              "<strong>Duration: </strong>{1:.1f} mins<br>" \
              "<strong>Distance: </strong>{2:.3f} km"

# Request route
coordinates = [[13.372582, 52.520295], [13.391476, 52.508856]]
direction_params = {
Esempio n. 14
0
import os
from pathlib import Path

from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import httpx
from openrouteservice import client
from openrouteservice.geocode import pelias_search as geocode

OPENROUTESERVICE_TOKEN = os.environ['OPENROUTESERVICE_TOKEN']
DGT_URL = 'http://infocar.dgt.es/etraffic/BuscarElementos?latNS=44&longNS=5&latSW=27&longSW=-19&zoom=6&accion=getElementos&Camaras=true&SensoresTrafico=true&SensoresMeteorologico=true&Paneles=true&Radares=true&IncidenciasRETENCION=true&IncidenciasOBRAS=false&IncidenciasMETEOROLOGICA=true&IncidenciasPUERTOS=true&IncidenciasOTROS=true&IncidenciasEVENTOS=true&IncidenciasRESTRICCIONES=true&niveles=true&caracter=acontecimiento'

openroute = client.Client(key=OPENROUTESERVICE_TOKEN)
app = FastAPI()
app.mount(
    "/static",
    StaticFiles(directory=Path(__file__).parent.parent.absolute() / "static"),
    name="static",
)

templates = Jinja2Templates(directory="templates")


@app.get("/")
async def root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})


@app.get("/events")
async def get_dgt_events():
Esempio n. 15
0
def update_map(n_clicks, add_start, add_end, fearlevel):
    if any([add_end is None, add_start is None]):
        return my_input().initial_map()
    else:
        # 1. Reverse-geocoding (i.e finding geo coordinates from addresses)
        # Also handles lat/long
        if re.match(r"(\d{1,2}\.\d{1,12})", add_start) is None:
            geocod_start = geocoder.osm(add_start)
            start_lat = geocod_start.lat
            start_lng = geocod_start.lng
        else:
            start_lat = float(add_start.split(" ")[0])
            start_lng = float(add_start.split(" ")[1])

        if re.match(r"(\d{1,2}\.\d{1,12})", add_end) is None:
            geocod_end = geocoder.osm(add_end)
            end_lat = geocod_end.lat
            end_lng = geocod_end.lng

        else:
            end_lat = float(add_end.split(" ")[0])
            end_lng = float(add_end.split(" ")[1])

        # 2. Compute the box to look for POI around
        box = [(start_lat, end_lng), (end_lat, end_lng), (end_lat, start_lng),
               (start_lat, start_lng)]

        poly_box = Polygon(box)
        poly_box = poly_box.buffer(0.005).simplify(0.05)

        # 3. Retrieve the POI in the area
        try:
            api = overpy.Overpass()
            result_nodes = api.query(
                "(node['shop']{0};node['amenity']{0};);out;".format(
                    str(poly_box.exterior.bounds)))
            result_areas = api.query(
                "(area['shop']{0};area['amenity']{0};);out;".format(
                    str(poly_box.exterior.bounds)))
        except overpy.exception.OverpassGatewayTimeout:
            return """<h1 style="color:white;">TOO MANY ELEMENTS ON THE WAY!</h1>"""

        # 4. Filter the POI in the box to keep only the points to be avoid
        # Loading the csv for the danger levels
        dang_list = pd.read_csv(os.path.join(
            APP_PATH, os.path.join("assets", "DangerScoreList.csv")),
                                delimiter=',')
        # Score the POI in the area
        nodes_score = add_score(
            dang_list, result_nodes
        )  # nodes_score is a list of overpy objects, with lat and lon info,

        dangers_poly = []  # sites_poly
        # I define dangerous a POI with score greater than 1
        for node in nodes_score:
            try:
                if node.tags['dangerscore'] >= fearlevel:
                    lat = node.lat
                    lon = node.lon

                    dangers_poly_coords = Point(
                        lon, lat).buffer(0.0005).simplify(0.05)
                    dangers_poly.append(dangers_poly_coords)
            except:
                pass

        danger_buffer_poly = [
        ]  # site_buffer_poly, which is the input for the avoid polygon option
        for danger_poly in dangers_poly:
            poly = Polygon(danger_poly)
            danger_buffer_poly.append(poly)

        # 5.Request the route
        route_request = {
            'coordinates': [[start_lng, start_lat], [end_lng, end_lat]],
            # Careful long then lat and not lat then long
            'format_out': 'geojson',
            'profile': 'foot-walking',
            'preference': 'shortest',
            'instructions': False,
            'options': {
                'avoid_polygons': mapping(MultiPolygon(danger_buffer_poly))
            }
        }

        api_key = '5b3ce3597851110001cf6248d14c60f017174b11b170ff63fdbf48b3'
        clnt = client.Client(key=api_key)

        try:
            route_directions = clnt.directions(**route_request)

        except openrouteservice.exceptions.ApiError:
            return """<h1 style="color:white;">MISSION TOO DANGEROUS!</h1>"""

        # 6.Display the route and the dangerous points
        # Create the base map
        map = folium.Map(tiles=my_input().map_background,
                         location=([start_lat, start_lng]),
                         zoom_start=14)  # Create map

        # Beginning and end markers
        folium.Marker([start_lat, start_lng],
                      popup='<i>Start:</i> <b>{}</b>'.format(add_start),
                      icon=folium.Icon(color="green",
                                       icon="street-view",
                                       prefix="fa")).add_to(map)

        folium.Marker([end_lat, end_lng],
                      popup='<i>End:</i> <b>{}</b>'.format(add_end),
                      icon=folium.Icon(icon="fa-check-square",
                                       prefix="fa")).add_to(map)

        # Plotting the route
        style_route = {'fillColor': 'green', 'color': 'green', "weight": 5}
        folium.features.GeoJson(data=route_directions,
                                name='Route',
                                style_function=lambda x: style_route,
                                overlay=True).add_to(map)

        # Plotting the dangerous areas
        # style_danger = {'fillColor': '#f88494', 'color': '#ff334f'}
        # folium.features.GeoJson(data=mapping(MultiPolygon(danger_buffer_poly)),
        #                         style_function=lambda x: style_danger,
        #                         overlay=True).add_to(map)

        # Adding icons (I haven't found dragons actually available :( )
        for node in nodes_score:
            if node.tags['dangerscore'] >= fearlevel:
                # Retrieve the type of place
                if "amenity" in node.tags:
                    type_place = node.tags["amenity"]
                else:
                    type_place = node.tags["shop"]

                # Create the markers
                if node.tags['dangerscore'] == 3:
                    folium.Marker([node.lat, node.lon],
                                  popup='<b>{}</b>'.format(type_place),
                                  icon=folium.features.CustomIcon(
                                      os.path.join(
                                          APP_PATH,
                                          os.path.join("assets", "skull.png")),
                                      icon_size=(30, 30))).add_to(map)

                elif node.tags['dangerscore'] == 2:
                    folium.Marker(
                        [node.lat, node.lon],
                        popup='<b>{}</b>'.format(type_place),
                        icon=folium.features.CustomIcon(
                            random.choice([
                                os.path.join(
                                    APP_PATH,
                                    os.path.join("assets",
                                                 "dragon1_purple.png")),
                                os.path.join(
                                    APP_PATH,
                                    os.path.join("assets", "spat.png")),
                                os.path.join(
                                    APP_PATH,
                                    os.path.join("assets", "dragon2.png"))
                            ]),
                            icon_size=(30, 30))).add_to(map)

                else:
                    folium.Marker([node.lat, node.lon],
                                  popup='<b>{}</b>'.format(type_place),
                                  icon=folium.features.CustomIcon(
                                      os.path.join(
                                          APP_PATH,
                                          os.path.join("assets", "ghost.png")),
                                      icon_size=(30, 30))).add_to(map)

        # Create legend
        # legend_html = """
        # <div style ="position: fixed; bottom: 50px; left: 50px; width: 200px;
        # height: 150px;z-index: 9999; font-size: 12px;"> <h5 style="font-family:verdana;">Legend</h5>
        # <div class="figure"> <img src="{0}"; width="25"; height="25"">&nbsp;High risk</div><br>
        # <div class="figure"> <img src="{1}"; width="25"; height="25">&nbsp;Medium risk</div><br>
        # <div class="figure"> <img src="{2}"; width="25"; height="25">&nbsp;Low</div><br>
        # </div>
        # """.format(os.path.join(APP_PATH, os.path.join("assets", "skull.png")),
        #            os.path.join(APP_PATH, os.path.join("assets", "dragon1_purple.png")),
        #            os.path.join(APP_PATH, os.path.join("assets", "ghost.png")))
        #
        # map.get_root().html.add_child(folium.Element(legend_html))

        # Add the lat long pop-up on click
        map.add_child(folium.LatLngPopup())

        return map._repr_html_()
Esempio n. 16
0
def seiu(lat, lon, time):
    print("")
    # request reverse geocoding
    r = requests.get(
        'https://api.opencagedata.com/geocode/v1/json?q=%s+%s&key=7e95a1a406154911b68bfff0a5bf9c34'
        % (lat, lon))
    results = r.json()
    where = results['results'][0]['formatted']
    print("Your location is:", where)

    # load csv
    df_ca = pd.read_csv('supporting documents/Dialysis_CA.csv')
    df_la = pd.read_csv('supporting documents/Dialysis_LA.csv')
    df_seiu = pd.read_csv('supporting documents/SEIU_UHW_CA.csv')

    # handle lat lon as floats
    df_seiu['lat'] = df_seiu['lat'].astype(float)
    df_seiu['lon'] = df_seiu['lon'].astype(float)

    df_ca['lat'] = df_ca['lat'].astype(float)
    df_ca['lon'] = df_ca['lon'].astype(float)

    df_la['lat'] = df_la['lat'].astype(float)
    df_la['lon'] = df_la['lon'].astype(float)

    # map
    map = folium.Map(location=[36.7783, -119.4179],
                     tiles='Stamen Toner',
                     zoom_start=5.5)

    # plugin for MeasureControl
    map.add_child(MeasureControl())

    # float image plugin for logo
    logo = ('https://i.imgur.com/WTmLCbc.png')
    justice = ('https://i.imgur.com/mJgkwHV.png')
    FloatImage(logo, bottom=8, left=4).add_to(map)
    FloatImage(justice, bottom=.5, left=4).add_to(map)

    fg = folium.FeatureGroup(name='Heat Map of Dialysis Clinics').add_to(map)
    heat_df = df_ca[['lat', 'lon']]
    heat_data = [[row['lat'], row['lon']] for index, row in heat_df.iterrows()]
    HeatMap(heat_data, radius=15, blur=17).add_to(fg)

    # clinics in CA
    clinic_df = df_ca[['lat', 'lon']]
    clinic_data = [[r['lat'], r['lon']] for i, r in clinic_df.iterrows()]

    fg_1 = folium.FeatureGroup(name='Dialysis Clinics').add_to(map)
    marker_cluster = MarkerCluster().add_to(fg_1)

    for point in range(0, len(clinic_data)):
        folium.Marker(clinic_data[point],
                      popup='<strong>' + "Facility: " +
                      df_ca['Facility N'][point] + " - Address:"
                      '</strong>' + df_ca['Address Li'][point],
                      icon=folium.Icon(color='beige',
                                       icon_color='darkpurple',
                                       icon='plus')).add_to(marker_cluster)

    # SEIU offices
    seiu_df = df_seiu[['lat', 'lon']]
    seiu_data = [[r['lat'], r['lon']] for i, r in seiu_df.iterrows()]

    fg_2 = folium.FeatureGroup(name='SEIU UHW Offices').add_to(map)
    for point in range(0, len(seiu_data)):
        folium.Marker(seiu_data[point],
                      popup='<strong>' + "SEIU Office: " +
                      df_seiu['SEIU UHW'][point] + " - Address:"
                      '</strong>' + df_seiu['Address'][point],
                      icon=folium.Icon(color='darkpurple',
                                       icon_color='white',
                                       icon='heart')).add_to(fg_2)

    folium.LayerControl(collapsed=False).add_to(map)

    map.save('MapFinal1.html')

    # Service Area
    loc = [[lon, lat]]
    loc_df = pd.DataFrame(loc, columns=['lon', 'lat'])
    org_df = loc_df[['lat', 'lon']]
    org_data = [[r['lat'], r['lon']] for i, r in org_df.iterrows()]

    map2 = folium.Map(location=[float(lat), float(lon)],
                      tiles='Stamen Toner',
                      zoom_start=11)

    FloatImage(logo, bottom=8, left=4).add_to(map2)
    FloatImage(justice, bottom=.5, left=4).add_to(map2)

    for point in range(0, len(org_data)):
        folium.Marker(org_data[point],
                      popup='<strong>'
                      "Your Input Location:" + where + '</strong>',
                      icon=folium.Icon(color='darkpurple',
                                       icon_color='white',
                                       icon='user')).add_to(map2)

    key = '5b3ce3597851110001cf6248c13297498fc24a73a4067bd7d1a87f7d'
    clnt = client.Client(key=key)

    # parameters for isochrones request
    params_iso = {
        'profile': 'driving-car',
        'range': [time * 60],
        'interval': time * 60
    }
    loc_dict = {'loc': {'location': [lon, lat]}}

    for name, loc in loc_dict.items():
        params_iso['locations'] = [loc['location']]
        iso = clnt.isochrones(**params_iso)
        folium.features.GeoJson(iso).add_to(map2)

    iso_buffer = Polygon(iso['features'][0]['geometry']['coordinates'][0])
    folium.features.GeoJson(data=mapping(iso_buffer),
                            name='Drive Time Isochrone',
                            overlay=True).add_to(map2)

    # reverse lat lon df
    clinic_r_a = df_ca[['lat', 'lon', 'Address Li', 'Facility N']]
    clinic_r_a_data = [[r['lon'], r['lat'], r['Address Li'], r['Facility N']]
                       for i, r in clinic_r_a.iterrows()]

    print("")
    print("Clinics within" + " " + str(time) + " " + "minute(s) of driving" +
          ": ")
    print("")
    for clinic in clinic_r_a_data:
        point = Point(clinic)
        if iso_buffer.contains(point):
            omglol = clinic[3] + " at " + clinic[2]
            folium.Marker(list(reversed(point.coords[0])),
                          popup='<strong>' + "Clinics within" + " " +
                          str(time) + " " + "minute(s) of driving" +
                          '</strong>' + ": " + omglol,
                          icon=folium.Icon(color='beige',
                                           icon_color='darkpurple',
                                           icon='plus')).add_to(map2)

    params_route = {
        'profile': 'driving-car',
        'format_out': 'geojson',
        'geometry': 'true',
        'format': 'geojson',
        'instructions': 'true',
        'preference': 'recommended'
    }

    def style_function(color):
        return lambda feature: dict(color=color, weight=3, opacity=1)

    for clinic in clinic_r_a_data:
        point = Point(clinic)
        for name, loc in loc_dict.items():
            org_coord = loc['location']
        if iso_buffer.contains(point):
            omglol = clinic[3] + " at " + clinic[2]
            clinic_coord = [clinic[0], clinic[1]]
            params_route['coordinates'] = [org_coord, clinic_coord]
            json_route = clnt.directions(**params_route)
            folium.features.GeoJson(
                json_route,
                style_function=style_function("#ffff00")).add_to(map2)
            folium.Marker(list(reversed(point.coords[0])),
                          popup='<strong>' + "Clinics within" + " " +
                          str(time) + " " + "minute(s) of driving" +
                          '</strong>' + ": " + omglol,
                          icon=folium.Icon(color='beige',
                                           icon_color='darkpurple',
                                           icon='plus')).add_to(map2)
            print(omglol)
            print("Driving distance in minute(s):")
            print(
                (json_route['features'][0]['properties']['summary']['duration']
                 ) / 60)
            print("")

    map2.save('MapFinal2.html')