Beispiel #1
0
    del twinA_MichiganID[i]
    del twinB_SVID[i]
    del twinB_MichiganID[i]
    del twinzygos[i]

for i in range(0,len(twinA_SVID)):
    print("At individual:",i+1)
    twinA = find(Michigan_ID, twinA_MichiganID[i])
    twinB = find(Michigan_ID, twinB_MichiganID[i])
    mapit = folium.Map(location=[IDlatlon[twinA[0]][1], IDlatlon[twinA[0]][2]], zoom_start=4)
    # create base map
    #(__mapit, __IDlatlon, __person, __subsetIndex, __twinIndex)
    mapitTwinA = baseLayer(mapit, IDlatlon, twinA, 1, 1, twinA_SVID[i]) #navy + white
    # plot twin A as twin reference with white square and number
    mapitTwinB = colorLayer(mapitTwinA, IDlatlon, twinB, 1, 2, twinB_SVID[i])#fuschia + default color
    # plot twin B with interactive layer and color
    folium.LayerControl().add_to(mapitTwinB)

    fileName = '{zygos}_{twinA}_{twinB}.html'.format(zygos = twinzygos[i], twinA = twinA_SVID[i], twinB=twinB_SVID[i])
    os.chdir('/Users/Shiloh/Box/Shiloh_Geography_Spring2019/foliumMap')# new directory
    mapitTwinB.save(fileName)

# for i in range(0,len(noPair)):
#     print('At individual:', i+1)
#     twin = find(Michigan_ID, noPair[i][0])
#     mapit = folium.Map(location = [IDlatlon[twin[0]][1], IDlatlon[twin[0]][2]], zoom_start =4 )
#     mapitTwinA = colorLayer(mapit, IDlatlon, twin, 1, 2, noPair[i][1])
#     folium.LayerControl().add_to(mapit)
#     fileName = '{twinSV}.html'.format(twinSV = noPair[i][1])
#     os.chdir('/Users/Shiloh/Box/Shiloh_Geography_Spring2019/foliumMap')
#     mapit.save(fileName)
Beispiel #2
0
        return 'orange'

# getting coordinates
(lst, height) = get_coordinates(data)

map = fl.Map(location=[40,-100])  #creating a map object
fgv = fl.FeatureGroup(name='Volcanoes')

# lst = [[13.357,74.79], [13.356,74.79], [13.358,74.79], [13.357,74.80]]
for coordinate, ele in zip(lst, height):
    fgv.add_child(fl.CircleMarker(location=coordinate, radius=6, popup="Elevation = {}".format(ele),
    fill_color=height_intensity(ele), color='grey', fill_opacity=0.6))

#adding popurlation polygon using geoJSON
fgp = fl.FeatureGroup(name='Popurlation')
fh = '''D:/Code/Python/Courses/The Python Mega Course Build 10 Real World Applications/11 Application 2 Creating Webmaps with Python and Folium/world.json'''
dat = open(fh, encoding="utf-8-sig").read()

fgp.add_child(fl.GeoJson(data=dat,
style_function = lambda x: {
'fillColor' : 'green' if x['properties']['POP2005'] < 10000000  # lesser than 10,000,000
else 'red' if x['properties']['POP2005'] > 20000000     # greater than 20,000,000
else 'orange'
}))

# adding to map
map.add_child(fgv)
map.add_child(fgp)
map.add_child(fl.LayerControl())
map.save('./index.html')  #creating and saving maps in html
Beispiel #3
0
def show_result_map(result=None,
                    items_list=[],
                    target_area=None,
                    overview=False):
    center = [38, 35]
    zoom = 6
    if not items_list:
        items = result.items()
        m = folium.Map(location=center, zoom_start=zoom)
        if target_area is not None:
            geo = target_area.__geo_interface__
            m.add_child(
                folium.GeoJson(geo,
                               name='Area of Study',
                               style_function=lambda x: {
                                   'color': 'red',
                                   'alpha': 0
                               }))
        for item in items:
            if overview:
                #get overview band
                #get overview band
                band_url = item.assets['thumbnail']['href']
                pol = Polygon(item.geometry['coordinates'][0])
                folium.raster_layers.ImageOverlay(
                    image=band_url,
                    name=item.properties['sentinel:product_id'],
                    bounds=[[
                        min(pol.exterior.coords.xy[1]),
                        min(pol.exterior.coords.xy[0])
                    ],
                            [
                                max(pol.exterior.coords.xy[1]),
                                max(pol.exterior.coords.xy[0])
                            ]],
                    #bounds=[item.geometry['coordinates'][0][0], item.geometry['coordinates'][0][3]],
                    opacity=1,
                    interactive=True,
                    cross_origin=True,
                    zindex=1,
                    #alt="Wikipedia File:Mercator projection SW.jpg",
                ).add_to(m)

            else:
                # Create a string for the name containing the path and row of this Polygon
                name = item.properties['sentinel:product_id']
                # Create the folium geometry of this Polygon
                g = folium.GeoJson(item.geometry, name=name)
                # Add a folium Popup object with the name string
                g.add_child(folium.Popup(name))
                # Add the object to the map
                g.add_to(m)

        folium.LayerControl().add_to(m)
        return m

    else:
        m = folium.Map(location=center, zoom_start=zoom)
        if target_area is not None:
            geo = target_area.__geo_interface__
            m.add_child(
                folium.GeoJson(geo,
                               name='Area of Study',
                               style_function=lambda x: {
                                   'color': 'red',
                                   'alpha': 0
                               }))

        for item in items_list:
            if overview:
                #get overview band
                band_url = item.assets['thumbnail']['href']
                pol = Polygon(item.geometry['coordinates'][0])
                folium.raster_layers.ImageOverlay(
                    image=band_url,
                    name=item.properties['sentinel:product_id'],
                    bounds=[[
                        min(pol.exterior.coords.xy[1]),
                        min(pol.exterior.coords.xy[0])
                    ],
                            [
                                max(pol.exterior.coords.xy[1]),
                                max(pol.exterior.coords.xy[0])
                            ]],
                    #bounds=[item.geometry['coordinates'][0][0], item.geometry['coordinates'][0][3]],
                    opacity=1,
                    interactive=True,
                    cross_origin=True,
                    zindex=1,
                    #alt="Wikipedia File:Mercator projection SW.jpg",
                ).add_to(m)

            else:
                # Create a string for the name containing the path and row of this Polygon
                name = item.properties['sentinel:product_id']
                # Create the folium geometry of this Polygon
                g = folium.GeoJson(item.geometry, name=name)
                # Add a folium Popup object with the name string
                g.add_child(folium.Popup(name))
                # Add the object to the map
                g.add_to(m)

        folium.LayerControl().add_to(m)
        return m
Beispiel #4
0
    def __init__(self, **kwargs):

        import logging

        logging.getLogger("googleapiclient.discovery_cache").setLevel(
            logging.ERROR)

        if "ee_initialize" not in kwargs.keys():
            kwargs["ee_initialize"] = True

        if kwargs["ee_initialize"]:
            ee_initialize()

        # Default map center location and zoom level
        latlon = [40, -100]
        zoom = 4

        # Interchangeable parameters between ipyleaflet and folium
        if "center" in kwargs.keys():
            kwargs["location"] = kwargs["center"]
            kwargs.pop("center")
        if "location" in kwargs.keys():
            latlon = kwargs["location"]
        else:
            kwargs["location"] = latlon

        if "zoom" in kwargs.keys():
            kwargs["zoom_start"] = kwargs["zoom"]
            kwargs.pop("zoom")
        if "zoom_start" in kwargs.keys():
            zoom = kwargs["zoom_start"]
        else:
            kwargs["zoom_start"] = zoom

        if "add_google_map" not in kwargs.keys(
        ) and "basemap" not in kwargs.keys():
            kwargs["add_google_map"] = True
        if "plugin_LatLngPopup" not in kwargs.keys():
            kwargs["plugin_LatLngPopup"] = True
        if "plugin_Fullscreen" not in kwargs.keys():
            kwargs["plugin_Fullscreen"] = True
        if "plugin_Draw" not in kwargs.keys():
            kwargs["plugin_Draw"] = False
        if "Draw_export" not in kwargs.keys():
            kwargs["Draw_export"] = True
        if "plugin_MiniMap" not in kwargs.keys():
            kwargs["plugin_MiniMap"] = False
        if "plugin_LayerControl" not in kwargs.keys():
            kwargs["plugin_LayerControl"] = False

        super().__init__(**kwargs)
        self.baseclass = "folium"

        if kwargs.get("add_google_map"):
            ee_basemaps["ROADMAP"].add_to(self)
        if kwargs.get("basemap"):
            ee_basemaps[kwargs.get("basemap")].add_to(self)
        if kwargs.get("plugin_LatLngPopup"):
            folium.LatLngPopup().add_to(self)
        if kwargs.get("plugin_Fullscreen"):
            plugins.Fullscreen().add_to(self)
        if kwargs.get("plugin_Draw"):
            plugins.Draw(export=kwargs.get("Draw_export")).add_to(self)
        if kwargs.get("plugin_MiniMap"):
            plugins.MiniMap().add_to(self)
        if kwargs.get("plugin_LayerControl"):
            folium.LayerControl().add_to(self)

        self.fit_bounds([latlon, latlon], max_zoom=zoom)
    popup=folium.Popup(max_width=500).add_child(
        folium.Vega(vis2, width=500, height=250))
).add_to(dat_grphs)

folium.Marker(
    location=[6.942936, 80.610974],
    icon=folium.Icon(color='blue', icon='bar-chart',
                     prefix='fa'),
    popup=folium.Popup(max_width=500).add_child(
        folium.Vega(vis3, width=500, height=250))
).add_to(dat_grphs)

plugins.HeatMap(datalist).add_to(sensor_hMap)

# add layer control:
folium.LayerControl(collapsed=True).add_to(tea_map)

# enable lat/lon popovers for convenience
tea_map.add_child(folium.LatLngPopup())

# vector drawing
plugins.Draw(
    export=False,
    filename='my_data.geojson',
    position='topleft',
    draw_options={'polyline': {'allowIntersection': False}},
    edit_options={'poly': {'allowIntersection': False}}
).add_to(tea_map)

# m.save(os.path.join('results', 'Plugins_1.html'))
Track colored by heart rate
===========================

This example will create a map and color the track according
to the measured heart rate.
"""
import folium
from gpxplotter import (
    read_gpx_file,
    create_folium_map,
    add_segment_to_map,
    add_all_tiles,
)

the_map = create_folium_map(tiles='kartverket_topo4')
# Add pre-defined tiles:
add_all_tiles(the_map)

for track in read_gpx_file('example1.gpx'):
    for i, segment in enumerate(track['segments']):
        add_segment_to_map(the_map, segment, color_by='hr')

# Add layer control to change tiles:
folium.LayerControl(sortLayers=True).add_to(the_map)

# To store the map as a HTML page:
# the_map.save('map_001.html')

# To display the map in a Jupyter notebook:
the_map
map_cctv = folium.Map(location=[35.22323, 128.60946], zoom_start=11, tiles='OpenStreetMap')

rfile = open("changwon.json", 'r', encoding='cp949').read()
jsonData = json.loads(rfile)
folium.GeoJson(jsonData, name='읍면동 구분').add_to(map_cctv)

# 4-3-5. 마우스 포지션(위도, 경도) 찾기 기능
# from folium.plugins import MousePosition
# MousePosition().add_to(map_cctv)

# 4-3-6. 측정도구 기능
# from folium.plugins import MeasureControl
# map_pplace.add_child(MeasureControl())
len(data[data['카메라대수'] == 4])

fg = folium.FeatureGroup(name="cctv 전체")  # 전체그룹 설정
g1 = plugins.FeatureGroupSubGroup(fg, '교통용 cctv')  # 서브그룹 틀 만들기
g2 = plugins.FeatureGroupSubGroup(fg, '비교통용 cctv')
map_cctv.add_child(fg)  # 서브 그룹 맵에 넣기
map_cctv.add_child(g1)
map_cctv.add_child(g2)
for i in range(0, len(data_traffic)):
    folium.Circle([data_traffic["위도"][i], data_traffic["경도"][i]], radius=50, color="#ffc039", fill=True).add_to(g1)
for j in range(0, len(data_non_traffic)):
    folium.Circle([data_non_traffic["위도"][j], data_non_traffic["경도"][j]], radius=50, color="#376091", fill=True).add_to(g2)

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

map_cctv.save("map_cctv.html")
Beispiel #8
0
for lati,lng in zip(Biblioteca.Lat,Biblioteca.Long):
    coordenadas.append([lati,lng])

Mapa = folium.Map(location=[33.0,65.0],zoom_start=5)

Mapa.add_child(plugins.HeatMap(coordenadas))

folium.Marker([33.0,65.0],popup='Afeganistão',tooltip='Click aqui',
                    icon=folium.Icon(color='green')).add_to(Mapa)

Mapa.add_child(folium.LatLngPopup())

draw = plugins.Draw(export=True,)
draw.add_to(Mapa)

folium.raster_layers.TileLayer('Open Street Map').add_to(Mapa)
folium.raster_layers.TileLayer('Stamen Terrain').add_to(Mapa)
folium.raster_layers.TileLayer('Stamen Toner').add_to(Mapa)
folium.raster_layers.TileLayer('Stamen watercolor').add_to(Mapa)
folium.raster_layers.TileLayer('CartoDB Positron').add_to(Mapa)
folium.raster_layers.TileLayer('CartoDB Dark_Matter').add_to(Mapa)

folium.LayerControl().add_to(Mapa)

minimap=plugins.MiniMap(toggle_display = True)
Mapa.add_child(minimap)
plugins.ScrollZoomToggler().add_to(Mapa)
plugins.Fullscreen(position = 'topright').add_to(Mapa)

Mapa.save("Casos no mundo.html")
        return "blue"
    else:
        return "red"

    
harita=folium.Map(location=[38.9597594, 34.9249653],zoom_start=7,tiles="Mapbox Control Room")
nufusHaritasi=folium.FeatureGroup(name="Nufus Haritasi")

for il,en,boy,nuf in zip(sehir,enlem,boylam,nufus):
    renk=Renklendir(int(nuf.replace(".","")))
    nufusHaritasi.add_child(folium.Marker(location=[en,boy],tooltip=(il+"  nüfus:"+nuf),icon=folium.Icon(color=renk)))



sehirIndex=pdSehirNufuslar.set_index("sehir")
def NufusKontrol(shr):
    sonuc=int(sehirIndex.loc[shr, 'nufus'].replace(".",""))
    return Renklendir(sonuc)


ilSinirlari=folium.FeatureGroup(name="İl sınırları")

ilSinirlari.add_child(folium.GeoJson(open("turkey-il-sinirlar.json","r",encoding="utf-8-sig").read(),
style_function=lambda il: {'fillColor':NufusKontrol(il["properties"]["Name"])}))


harita.add_child(nufusHaritasi)    
harita.add_child(ilSinirlari)
harita.add_child(folium.LayerControl())
harita.save("turkey.html")
Beispiel #10
0
def create_markup_map(name: str, df: pd.core.frame.DataFrame):
    """Place a markup for each point with a valid
    housing price evaluation and position
    """
    map_ = folium.Map(
        location=france_location,
        zoom_start=3,
        control_scale=True,
        tiles="openstreetmap",
    )
    mcg = folium.plugins.MarkerCluster(control=False)
    map_.add_child(mcg)

    houses = folium.plugins.FeatureGroupSubGroup(mcg, "houses")
    appartements = folium.plugins.FeatureGroupSubGroup(mcg, "appartements")
    others = folium.plugins.FeatureGroupSubGroup(mcg, "others")
    map_.add_child(houses)
    map_.add_child(appartements)
    map_.add_child(others)

    for _, row in df.iterrows():
        housing_type = row["Type local"]
        if housing_type == "Maison":
            color = "darkgreen"
            icon = "home"
            context = houses

        elif housing_type == "Appartement":
            color = "red"
            icon = "pause"
            context = appartements
        else:
            color = "black"
            icon = "info-sign"
            context = others

        price = int(row["Valeur fonciere"])
        address = get_address_from_row(row)
        context.add_child(
            folium.Marker(
                (row["lat"], row["lon"]),
                popup=folium.Popup(
                    f"{housing_type}</br> {address} <b>{price}€</b>",
                    # Not working properly
                    max_width="400px",
                    min_width="200px",
                ),
                tooltip=housing_type,
                icon=folium.Icon(color=color, icon=icon),
            )
        )

    map_.add_child(
        plugins.Fullscreen(
            position="topright",
            title="Expand me",
            title_cancel="Exit me",
            force_separate_button=True,
        )
    )
    map_.add_child(folium.LayerControl(collapsed=False))
    map_.add_child(plugins.MeasureControl())
    map_.add_child(plugins.MiniMap())
    save_map(map_, name)
Beispiel #11
0
        'weight': 0.3,
        'fillOpacity': 0.5 if x['id'] in person['States'] else 0.0
    }


def states_traveled(person, color):
    """
    Take a person's name and a color to create GeoJson overlay
    for states that the person has traveled to.
    Color will be used in style function for fill.
    Adds overlay to map.
    """
    folium.GeoJson(data=state_geo,
                   name=person['Name'] + ' - ' + str(len(person['States'])),
                   style_function=state_style(person, color)).add_to(us_map)


'''
EXAMPLE CODE:

person_1 = {
    'Name' : 'Person 1',
    'States' : ['ME', 'FL', 'CA', 'WA', 'OR']
}

states_traveled(person_1, 'red')
'''

folium.LayerControl(hideSingleBase=True).add_to(us_map)
us_map.save('us_map.html')
    if elev in range(minimum, minimum + step_value):
        color = 'green'
    elif elev in range(minimum, minimum + step_value * 2):
        color = 'orange'
    else:
        color = 'red'
    return color


# Add the feature group created above to be able to filter out the icons in the Layer Control
feature_group = folium.FeatureGroup(name='Volcano Locations')

# Add markers one by one using the data range defined in your dataset
for lat, lon, name, elevation in zip(data['LAT'], data['LON'], data['NAME'], data['ELEV']):
    feature_group.add_child(folium.Marker(location=[lat, lon], popup=name,
                                          icon=folium.Icon(marker_color(elevation), icon_color='black'))).add_to(my_map)

geojson_layer = my_map.add_child(
    folium.GeoJson(json.load(open('data_files/world_population.json')),
                   name='World Population',
                   style_function=lambda x: {'fillColor': 'green' if x['properties']['POP2005'] <= 10000000
                   else 'orange' if 10000000 < x['properties']['POP2005'] <= 20000000 else 'red'}))

layer_controller = my_map.add_child(folium.LayerControl(position='topright', collapsed=True))

# Save the folium map to a directory as an html file
my_map.save(outfile='output_files/west-coast_map.html')

print('Creating a webmap for Volcanoes in the US...')
Beispiel #13
0
def mapping(date):
    df = readfile(date)
    # create empty map zoomed in on San Francisco
    m = folium.Map(location=(39, -98), zoom_start=4)
    folium.TileLayer('openstreetmap').add_to(m)

    cluster1 = folium.plugins.MarkerCluster(name="Not Relevant").add_to(m)
    cluster2 = folium.plugins.MarkerCluster(name="Relevant").add_to(m)

    # add a marker for every record in the filtered data, use a clustered view
    for i in df.index:
        if df.loc[i, 'relevant'] == 0:
            tweet = df.loc[i, 'text']
            location = (df.loc[i, 'twlong'], df.loc[i, 'twlat'])
            state = df.loc[i, 'state']
            county = df.loc[i, 'name']
            url = df.loc[i, 'url']
            folium.Marker(
                location=[df.loc[i, 'twlat'], df.loc[i, 'twlong']],
                popup=
                '<b>Tweet: </b>%s<br></br><b>Location: </b>%s<br></br><b>State: </b>%s<br></br><b>County: </b>%s<br></br><b>URL: </b><a href="%s" target="_blank">%s</a>'
                % (tweet, location, state, county, url, url),
                icon=folium.Icon(icon='fire', color='red')).add_to(cluster1)

        elif df.loc[i, 'relevant'] == 1:
            tweet = df.loc[i, 'text']
            location = (df.loc[i, 'twlong'], df.loc[i, 'twlat'])
            state = df.loc[i, 'state']
            county = df.loc[i, 'name']
            url = df.loc[i, 'url']
            folium.Marker(
                location=[df.loc[i, 'twlat'], df.loc[i, 'twlong']],
                popup=
                '<b>Tweet: </b>%s<br></br><b>Location: </b>%s<br></br><b>State: </b>%s<br></br><b>County: </b>%s<br></br><b>URL: </b><a href="%s" target="_blank">%s</a>'
                % (tweet, location, state, county, url, url),
                icon=folium.Icon(icon='fire', color='red')).add_to(cluster2)

    # add circle for searching
    #for j in df.index:
    #    folium.CircleMarker(location = [df.loc[j,'Latitude'],df.loc[j,'Longitude']],
    #                        radius = 10,
    #                        color = '#FF0000',
    #                        fill = True,
    #                        fill_color = '#FF0000').add_to(m)

    statedf = pd.DataFrame()
    ind = df[['Latitude', 'Longitude']].drop_duplicates().index
    df.loc[ind, 'state'].value_counts()
    statedf['state'] = df.loc[ind, 'state'].value_counts().index
    statedf['value'] = df.loc[ind, 'state'].value_counts().values
    statedf
    wholestate = statename.merge(statedf,
                                 left_on='name',
                                 right_on='state',
                                 how='left').drop(['state', 'abbreviation'],
                                                  axis=1).fillna(0)

    m.choropleth(
        geo_data=states,
        name='# of Fire detected',
        data=wholestate,
        columns=['name', 'value'],
        key_on='feature.properties.name',
        fill_color='YlOrRd',
        fill_opacity=0.7,
        line_opacotu=0.2,
        legend_name='Fire Count',
    )

    folium.LayerControl().add_to(m)
    m.add_child(MeasureControl())

    filepath = f'../{date}map.html'
    m.save(filepath)
Beispiel #14
0
def index():
    if flask.request.args.get('date') == None:

        return flask.render_template('index.html',
                                     dates=dates,
                                     phenom=m_type,
                                     months=month)

    date = int(flask.request.args.get('date'))
    month_selected = flask.request.args.get('months')
    phenom_long = flask.request.args.get('phenom')
    duration = int(flask.request.args.get('duration'))
    for key, name in CATEGORIES.iteritems():
        if name == phenom_long:
            phenom = key

    choosed_month, year = month_selected.split('/')
    try:
        start_date = datetime.datetime(int(year), int(choosed_month), date, 00,
                                       00, 00)
        end_date = datetime.datetime(int(year), int(choosed_month), date, 23, 59, 59) + \
        datetime.timedelta(days=duration)
    except:
        return flask.render_template('error.html',
                                     dates=dates,
                                     phenom=m_type,
                                     months=month,
                                     error='date')

    # http://stackoverflow.com/questions/12438990/select-records-from-postgres-where-timestamp-is-in-certain-rangsoure
    if phenom_long == 'temperature':
        sql_sensor = "SELECT DISTINCT idsensor FROM data where (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CA' or measuretype = 'ST');" % (
            start_date, end_date)

    elif phenom_long == 'humidity':
        sql_sensor = "SELECT DISTINCT idsensor FROM data where (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CB' or measuretype = 'SH');" % (
            start_date, end_date)
    else:
        sql_sensor = "SELECT DISTINCT idsensor FROM data where (timestamp > '%s' and timestamp < '%s') and measuretype = '%s';" % (
            start_date, end_date, str(phenom))

    holice_map = folium.Map(MAP_CENTER, zoom_start=18, tiles=None)
    folium.TileLayer('OpenStreetMap').add_to(holice_map)
    folium.TileLayer('MapQuestOpen').add_to(holice_map)
    # Map.add_children(folium.plugins.ImageOverlay(...))
    # ICON_URL = 'static/python.jpg'
    holice_map.add_children(
        plugins.ImageOverlay(
            ICON_URL,
            [PICTURE_COORS],
            opacity=0.5,
        ))
    # folium.LayerControl().add_to(holice_map)
    holice_map.add_children(folium.LayerControl())

    cur.execute(sql_sensor)
    # list of sensors [int,int,int], instead of [(int,), (int,), (int,)]
    sensors = [i[0] for i in cur.fetchall()]

    multi_iter1 = {}
    locations, popups = [], []
    for sensor_sql in sensors:
        # print sensor_sql

        for sensor in SENSOR:
            # print sensor
            if sensor[0] == sensor_sql:
                sensor_start_date = datetime.datetime.strptime(
                    sensor[2], "%Y-%m-%d")
                sensor_end_date = datetime.datetime.strptime(
                    sensor[3], "%Y-%m-%d %H:%M:%S")
                start_date_new = start_date
                end_date_new = end_date
                # print str(end_date) + ' > ' + str(sensor_start_date)
                # sensor have to not end measurement before start date and not start measurement after the end of end day
                if end_date >= sensor_start_date and start_date <= sensor_end_date:
                    # if sensor start measurement after start day, the start day will be replaced by sensor start day
                    # if value of start_date and end_date will be replaced, end of sensor measurement after end_date will not be replaced
                    if sensor_start_date > start_date:
                        #print start_date, sensor_start_date
                        start_date_new = sensor_start_date
                    if sensor_end_date < end_date:
                        #print end_date, sensor_end_date
                        end_date_new = sensor_end_date  # + datetime.timedelta(days=duration)

                    sensor_data = {}
                    if phenom_long == 'temperature':
                        sql_data_sensor = "SELECT measurevalue, timestamp FROM data WHERE (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CA' or measuretype = 'ST') and idsensor = %d;" % (
                            start_date_new, end_date_new, int(sensor[0]))
                    elif phenom_long == 'humidity':
                        sql_data_sensor = "SELECT measurevalue, timestamp FROM data WHERE (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CB' or measuretype = 'SH') and idsensor = %d;" % (
                            start_date_new, end_date_new, int(sensor[0]))
                    else:
                        sql_data_sensor = "SELECT measurevalue, timestamp FROM data WHERE (timestamp > '%s' and timestamp < '%s') and measuretype = '%s' and idsensor = %d;" % (
                            start_date_new, end_date_new, str(phenom),
                            int(sensor[0]))
                    print sql_data_sensor
                    cur.execute(sql_data_sensor)
                    # sort tuples by time_pattern
                    sql_data = sorted(list(cur.fetchall()),
                                      key=lambda time: time[1])

                    for row in sql_data:
                        # http://stackoverflow.com/questions/16198606/python-linux-timestamp-to-date-time-and-reverse
                        # https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
                        time_index = int(
                            time.mktime(
                                time.strptime(str(row[1]),
                                              "%Y-%m-%d %H:%M:%S")) * 1000)
                        # some data do not have measurevalue (83k rows)

                        if row[0]:
                            value = float(row[0])
                        else:
                            value = 0.0
                        sensor_data[time_index] = value

                    multi_iter1[sensor[0]] = sensor_data
                    # if there are no data

                    if multi_iter1[sensor[0]]:
                        vis = vincent.Line(multi_iter1[sensor[0]],
                                           width=600,
                                           height=200)
                        x_axis_str = 'data for sensor (' + str(
                            sensor[0]) + '). Time period: ' + str(
                                start_date_new) + ' to ' + str(end_date_new)
                        vis.axis_titles(x=str(x_axis_str), y=phenom_long)

                        vis._axis_properties(axis='y',
                                             title_size=15,
                                             title_offset=-10,
                                             label_align='right',
                                             label_angle=0,
                                             color='#000000')
                        vis.scales['x'] = vincent.Scale(name='x',
                                                        type='time',
                                                        range='width',
                                                        domain=vincent.DataRef(
                                                            data='table',
                                                            field="data.idx"))
                        vis.scales['y'] = vincent.Scale(name='y',
                                                        type='linear',
                                                        range='height',
                                                        domain=vincent.DataRef(
                                                            data='table',
                                                            field="data.val"))

                        vis.to_json('static/vis_%s.json' % sensor[0])

                        popups.append(
                            folium.Popup(max_width=1900).add_child(
                                folium.Vega(json.load(
                                    open('static/vis_%s.json' % sensor[0])),
                                            width="100%",
                                            height="100%")))

                        locations.append(sensor[1])

    if not locations:
        return flask.render_template('error.html',
                                     dates=dates,
                                     phenom=m_type,
                                     months=month,
                                     error='locations')
    holice_map.add_children(plugins.MarkerCluster(locations, popups))

    holice_map.save('templates/map.html')

    return flask.render_template('map.html')
Beispiel #15
0
def map_trips(feed,
              trip_ids,
              color_palette=cs.COLORS_SET2,
              *,
              include_stops=True):
    """
    Return a Folium map showing the given trips and (optionally)
    their stops.

    Parameters
    ----------
    feed : Feed
    trip_ids : list
        IDs of trips in ``feed.trips``
    color_palette : list
        Palette to use to color the routes. If more routes than colors,
        then colors will be recycled.
    include_stops : boolean
        If ``True``, then include stops in the map

    Returns
    -------
    dictionary
        A Folium Map depicting the shapes of the trips.
        If ``include_stops``, then include the stops for each trip.

    Notes
    ------
    - Requires Folium

    """
    import folium as fl
    import folium.plugins as fp

    # Get routes slice and convert to dictionary
    trips = (feed.trips.loc[lambda x: x["trip_id"].isin(trip_ids)].fillna(
        "n/a").to_dict(orient="records"))

    # Create colors
    n = len(trips)
    colors = [color_palette[i % len(color_palette)] for i in range(n)]

    # Initialize map
    my_map = fl.Map(tiles="cartodbpositron")

    # Collect route bounding boxes to set map zoom later
    bboxes = []

    # Create a feature group for each route and add it to the map
    for i, trip in enumerate(trips):
        collection = feed.trip_to_geojson(trip_id=trip["trip_id"],
                                          include_stops=include_stops)
        group = fl.FeatureGroup(name="Trip " + trip["trip_id"])
        color = colors[i]

        for f in collection["features"]:
            prop = f["properties"]

            # Add stop
            if f["geometry"]["type"] == "Point":
                lon, lat = f["geometry"]["coordinates"]
                fl.CircleMarker(
                    location=[lat, lon],
                    radius=8,
                    fill=True,
                    color=color,
                    weight=1,
                    popup=fl.Popup(hp.make_html(prop)),
                ).add_to(group)

            # Add path
            else:
                # Path
                prop["color"] = color
                path = fl.GeoJson(
                    f,
                    name=trip,
                    style_function=lambda x:
                    {"color": x["properties"]["color"]},
                )
                path.add_child(fl.Popup(hp.make_html(prop)))
                path.add_to(group)

                # Direction arrows, assuming, as GTFS does, that
                # trip direction equals LineString direction
                fp.PolyLineTextPath(
                    path,
                    "        \u27A4        ",
                    repeat=True,
                    offset=5.5,
                    attributes={
                        "fill": color,
                        "font-size": "18"
                    },
                ).add_to(group)

                bboxes.append(sg.box(*sg.shape(f["geometry"]).bounds))

        group.add_to(my_map)

    fl.LayerControl().add_to(my_map)

    # Fit map to bounds
    bounds = so.unary_union(bboxes).bounds
    bounds2 = [bounds[1::-1], bounds[3:1:-1]]  # Folium expects this ordering
    my_map.fit_bounds(bounds2)

    return my_map
            elif wind['Wind direction'][j]=='西南':
                 x=10;
            elif wind['Wind direction'][j]=='西南西':
                 x=11;
            elif wind['Wind direction'][j]=='西':
                 x=12;
            elif wind['Wind direction'][j]=='西北西':
                 x=13;
            elif wind['Wind direction'][j]=='西北':
                 x=14;
            elif wind['Wind direction'][j]=='北北西':
                 x=15;
            elif wind['Wind direction'][j]=='靜風':
                 x=0;

            station2.add_child(folium.Marker(
                                                location=[wind['Latitude'][j],wind['Longitude'][j]],
                                                popup=("<b>NAME:</b> {NAME}<br>""<b>Wind speed:</b> {Windspeed}<br>""<b>Wind direction:</b> {winddirection}<br>""<b>TIME:</b> {TIME}<br>")
                                                        .format(NAME=str(wind['Sitename'][j]),Windspeed=str(wind['Wind speed'][j]),winddirection=str(wind['Wind direction'][j]),TIME=str(tim$
                                                icon=folium.CustomIcon(wind_icon_url[x],icon_size=(27,27))
                                              )
                              )

fmap.add_child(station)
fmap.add_child(station2)
folium.LayerControl().add_to(fmap)
# lat/lon to map
# folium.LatLngPopup().add_to(fmap)
fmap.save('/var/www/html/epa2') #存成 final.html

Beispiel #17
0
    fgv.add_child(
        folium.Marker(
            location=[lt, ln],
            popup=folium.Popup(iframe),
            #adding different colors of markers based on elevation
            #create a function that returns the str based on the elevation
            icon=folium.Icon(color=color_producer(el))))

#add more dimension to the map - Polygon
#add style that colors the map based on population

fgp.add_child(
    folium.GeoJson(
        data=open('world.json', 'r', encoding='utf-8-sig').read(),
        #lambda functions are just functions but in a single line
        style_function=lambda x: {
            'fillColor':
            'yellow' if x['properties']['POP2005'] < 1000000 else 'oranange'
            if 1000000 <= x['properties']['POP2005'] < 20000000 else 'red'
        }))

map.add_child(fgv)
map.add_child((fgp))

#add an element that tuns on/off these base layers - use layerControl class of folium
map.add_child(folium.LayerControl(
))  #you dont want to use this because it can turn off all the features
#so make separate feature groups for each layer

map.save("Map3.html")

for n, lt, ln, el, ty in zip(name, lat, lon, elev, type):
    #volcano.add_child(folium.Marker(location=[lt,ln], popup=str(el) + "m \nType: " + ty, tooltip = n, icon = folium.Icon(color = elevation_color(el))))

    usa_volcano.add_child(
        folium.CircleMarker(location=[lt, ln],
                            radius=6,
                            popup=str(el) + "m \n Type: " + ty,
                            tooltip=n,
                            fill_color=elevation_color(el),
                            color='grey',
                            fill_opacity=0.9))

# this will access the json file, and will use properties and pop2005 to color code countries based on their population
pop.add_child(
    folium.GeoJson(
        data=open('world.json', 'r', encoding='utf-8-sig').read(),
        style_function=lambda x: {
            'fillColor':
            'darkgreen' if x['properties']['POP2005'] < 10000000 else 'beige'
            if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red'
        }))

map.add_child(pop)
map.add_child(usa_volcano)
map.add_child(
    folium.LayerControl()
)  # This will store pop and volcano as different layers that can be turned on and off in the HTML file
map.save("Map1.html")  # This saves the map as an HTML file called Map1
def makemap(lst):

    geomap = folium.Map([23.75, 121], zoom_start=8, tiles="cartodbpositron")
    folium.TileLayer('stamenterrain').add_to(geomap)
    folium.TileLayer('openstreetmap').add_to(geomap)

    colors = ["#FFFFFF", "#FFAAAA", "#FF6666","#FF6666", "#FF6666","#FF6666",
              "#FF0000","#FF0000","#FF0000","#FF0000"] 
    cm     = branca.colormap.LinearColormap(colors, vmin=0, vmax=1).to_step(len(colors))
    cm.caption = 'EI value'
    geomap.add_child(cm)
    sp,*pred = lst
    dfsp = pd.read_csv("../output_csv/combine/{}.csv".format(sp))
    tl1 = get_list(dfsp,2)
    if len(pred) == 1:
        pred1 = pd.read_csv("../output_csv/combine/{}.csv".format(pred[0]))
        tl2 =  get_list(pred1,1,ref=True)
        tl3 = []
    elif len(pred) == 2:
        pred1 = pd.read_csv("../output_csv/combine/{}.csv".format(pred[0]))
        pred2 = pd.read_csv("../output_csv/combine/{}.csv".format(pred[1]))
        tl2 =  get_list(pred1,1,ref=True)
        tl3 =  get_list(pred2,3,ref=True)
    else:
        tl2 = tl3 = []
    features = add_station(dfsp,sp)
    FC = tl1 + tl2 + tl3 + features
    plugins.TimestampedGeoJson(
        {
            'type': 'Feature',
            'features': FC

        },
        period='P1M',
        duration='P15D',
        auto_play=False,
        loop=False,
        loop_button=True,
        date_options='YYYY/MM',
    ).add_to(geomap)


    plugins.Fullscreen(position='topright', force_separate_button=True).add_to(geomap)
    plugins.MiniMap().add_to(geomap)
    plugins.MeasureControl(primary_length_unit='kilometers', 
                         secondary_length_unit='meters', 
                         primary_area_unit='hectares', 
                         secondary_area_unit='sqmeters').add_to(geomap)
    formatter = "function(num) {return L.Util.formatNum(num, 3) + ' º ';};"

    plugins.MousePosition(
        position='bottomleft',
        separator=' | ',
        empty_string='NaN',
        lng_first=True,
        num_digits=20,
        prefix='Coordinates:',
        lat_formatter=formatter,
        lng_formatter=formatter
    ).add_to(geomap)
    geomap.add_child(folium.LayerControl(position="topleft"))
#    return geomap
    geomap.save('../html/{}.html'.format(sp))
Beispiel #20
0
def main():

    ## Creating the base map object
    map_ = folium.Map(location=[40.2171, -74.7429],
                      zoom_start=5,
                      tiles='stamenwatercolor')

    def map_save(map_obj=map_, open_=True):

        map_obj.save("webmap1.html")
        ## This will control the browser to open up the html file
        if open_ == True:
            webbrowser.open_new_tab(os.path.realpath("webmap1.html"))

# -------------------------------------------------------------------------------------

## Adding multiple markers

    fg1 = folium.FeatureGroup(name="State_Markers")

    ## Reading in the state lat long dataframe
    try:
        ## If the file does not exist in directory
        df = pd.read_csv("State_Lat_Long.csv")
    except:
        ## The function will be called to recall the source data and create the file
        print("File not in Directory.")
        df = scraper()
        print("File Created and loaded")

    ## This is a csv I created when scraping and editing the json in the AddingPopulationToJson python File
    population_df = pd.read_csv("State_Population.csv")

    df['State'] = df["State"].apply(lambda x: x.strip())

    #print(df)
    #print(population_df)

    df = pd.merge(df, population_df, left_on="State", right_on="State")

    #    df.drop(["Unamed: 0_x", "Unamed: 0_y"], axis = 1, inplace = True)
    for i, k in df.iterrows():
        fg1.add_child(
            folium.Marker(location=[k[1], k[2]],
                          tooltip="State: {} - Click For Detail".format(k[0]),
                          popup="POP: {}   POP_DENSITY: {} (p/m^2)".format(
                              k[3], k[4]),
                          icon=folium.Icon(color='blue')))

# -------------------------------------------------------------------------------------

## Reading in the state capital data, and appending it to the web map
    state_df = pd.read_json("us_state_capitals.json", 'index')

    ## Creating a group to add the next batch of data into
    fg2 = folium.FeatureGroup(name='State_Capitals')
    ## Iterating over the rows in dataframe and appending it to the map
    for i, k in state_df.iterrows():
        fg2.add_child(
            folium.CircleMarker(location=[k[1], k[2]],
                                popup="{}".format(k[0]),
                                tooltip="State Capital - Click for Detail",
                                color='green',
                                fill_color='green',
                                fill_opacity=1))
    ## Adding all of the edits to the file

# -------------------------------------------------------------------------------------

## Playing around with volcano data.
    fg3 = folium.FeatureGroup(name="Volcanoes")
    with open("Volcanoes.txt", "r") as f:
        ## Rearding a list of lines from the stream above
        contents = f.readlines()
        #[print(i) for i in contents[:5]]

    df_volcanoes = pd.read_csv("Volcanoes.txt")

    ## Calculating the range and 3 steps for the elevation values
    ## This will be used to bin the volcanoes into 3 categories
    min_ = min(df_volcanoes['ELEV'])
    max_ = max(df_volcanoes["ELEV"])
    range_ = max_ - min_
    step_ = range_ / 3
    step1 = min_ + step_
    step2 = step1 + step_
    step3 = step2 + step_

    def step_finder(x, step1, step2, step3):
        """
        This function will return colors based on where the value x falls in relation to the 3 bins above
        """
        if x <= step1:
            return "pink"
        elif (x <= step2) and (x > step1):
            return "orange"
        else:
            return "red"

    for i, k in df_volcanoes.iterrows():
        color_ = step_finder(float(k[5]), step1, step2, step3)
        fg3.add_child(
            folium.CircleMarker(
                location=[k[8], k[9]],
                popup="NAME: {} \n\nTYPE: {} \n\nELEVATION: {}".format(
                    k[2], k[4], k[5]),
                tooltip="Volcano! - Click for Detail",
                fill_color=color_,
                color="grey",
                fill_opacity=0.8))


# -------------------------------------------------------------------------------------
## Adding polygon layer to the map

## Loading in the geojson data:

    fg4 = folium.FeatureGroup(name="Country_Polygon")

    fg4.add_child(
        folium.GeoJson(
            data=open("world.json", "r", encoding="utf-8-sig").read()))

    ## Adding the State Poly to the map:

    fg5 = folium.FeatureGroup(name="United_State_Population_Chloro_layer")

    fg5.add_child(
        folium.GeoJson(
            data=open("state_updated.json", "r").read(),
            style_function=lambda x: {
                "fillColor":
                "green" if int(x['properties']['Pop']) < 500000 else "yellow"
                if 500000 <= int(x['properties']['Pop']) < 10000000 else
                "orange" if 10000000 <= int(x['properties']['Pop']
                                            ) < 25000000 else "red"
            },
        ))

    ## Inserting them by layer:
    map_.add_child(fg4)
    map_.add_child(fg5)
    map_.add_child(fg1)
    map_.add_child(fg2)
    map_.add_child(fg3)

    ## Adding layer control to the map_
    map_.add_child(folium.LayerControl())

    # -------------------------------------------------------------------------------------
    ## Saving and plotting the map
    open_map = input("Open map? [y/n] ")
    if open_map.lower() == 'y':
        open_map = True
    else:
        open_map = False
    map_save(open_=open_map)

    return None
Beispiel #21
0
    for point in dataset['geometry']:
        CircleMarker(location=[point.y, point.x],
                     radius=4,
                     color=color,
                     fill_color=color).add_to(feature_group)

    feature_group.add_to(mapname)


### Make map

# First create basemap
boston_map = folium.Map([latitude, longitude],
                        tiles='Cartodb dark_matter',
                        zoom_start=12)
folium.TileLayer('Cartodb Positron').add_to(boston_map)

# Create sequence of colors so different layers appear in different colors
colors = ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854']

# Plot data as separate layers
for i in range(len(match)):
    data = process_data(match[i][1])
    add_layer(data, match[i][0], boston_map, colors[i])

# Add control to toggle between model layers
folium.LayerControl(position='bottomright').add_to(boston_map)

# Save map as separate html file
boston_map.save('plot_points.html')
Beispiel #22
0
def map_trips(
    feed: "Feed",
    trip_ids: Iterable[str],
    color_palette: list[str] = cs.COLORS_SET2,
    *,
    include_stops: bool = False,
    include_arrows: bool = False,
):
    """
    Return a Folium map showing the given trips and (optionally)
    their stops.
    If any of the given trip IDs are not found in the feed, then raise a ValueError.
    If ``include_arrows``, then use the Folium plugin PolyLineTextPath to draw arrows
    on each trip polyline indicating its direction of travel; this fails to work in some
    browsers, such as Brave 0.68.132.
    """
    # Initialize map
    my_map = fl.Map(tiles="cartodbpositron")

    # Create colors
    n = len(trip_ids)
    colors = [color_palette[i % len(color_palette)] for i in range(n)]

    # Collect bounding boxes to set map zoom later
    bboxes = []

    # Create a feature group for each route and add it to the map
    for i, trip_id in enumerate(trip_ids):
        collection = trips_to_geojson(feed, [trip_id],
                                      include_stops=include_stops)

        group = fl.FeatureGroup(name=f"Trip {trip_id}")
        color = colors[i]

        for f in collection["features"]:
            prop = f["properties"]

            # Add stop if present
            if f["geometry"]["type"] == "Point":
                lon, lat = f["geometry"]["coordinates"]
                fl.CircleMarker(
                    location=[lat, lon],
                    radius=8,
                    fill=True,
                    color=color,
                    weight=1,
                    popup=fl.Popup(hp.make_html(prop)),
                ).add_to(group)

            # Add trip
            else:
                path = fl.PolyLine(
                    [[x[1], x[0]] for x in f["geometry"]["coordinates"]],
                    color=color,
                    popup=hp.make_html(prop),
                )

                path.add_to(group)
                bboxes.append(sg.box(*sg.shape(f["geometry"]).bounds))

                if include_arrows:
                    # Direction arrows, assuming, as GTFS does, that
                    # trip direction equals LineString direction
                    fp.PolyLineTextPath(
                        path,
                        "        \u27A4        ",
                        repeat=True,
                        offset=5.5,
                        attributes={
                            "fill": color,
                            "font-size": "18"
                        },
                    ).add_to(group)

        group.add_to(my_map)

    fl.LayerControl().add_to(my_map)

    # Fit map to bounds
    bounds = so.unary_union(bboxes).bounds
    # Folium wants a different ordering
    bounds = [(bounds[1], bounds[0]), (bounds[3], bounds[2])]
    my_map.fit_bounds(bounds)

    return my_map
Beispiel #23
0
def calculate_dis(request):

    distance = None

    form = MeasurementModelForm(request.POST or None)
    geolocator = Nominatim(user_agent="measurement")

    trak = geocoder.ip('me')
    ip = trak.ip
    # ip='47.30.209.199'
    country, city, lat, long = get_geo(ip)
    # print("country",country)
    # print(f"Location {city['city']}, {city['region']}, {city['country_name']}, {city['country_code']}" )
    # print("city",)
    # print('country_code',)
    # print('region',)
    # print("lat",lat)
    # print("lon",long)
    l_lat = lat
    l_long = long
    pointa = (l_lat, l_long)

    map = folium.Map(location=(l_lat, l_long))
    folium.Marker(
        location=[l_lat, l_long],
        raduis=5,
        tooltip=
        f"{city['city']}, {city['region']}, {city['country_name']}, {city['country_code']}",
        icon=folium.Icon(color="red")).add_to(map)
    folium.TileLayer('Mapbox Control Room').add_to(map)
    folium.TileLayer('Stamen Toner').add_to(map)
    folium.TileLayer('Stamen Terrain').add_to(map)
    folium.TileLayer('Stamen Watercolor').add_to(map)
    folium.TileLayer('CartoDB positron').add_to(map)
    folium.TileLayer('CartoDB dark_matter').add_to(map)

    if form.is_valid():

        instance = form.save(commit=False)

        locat = form.cleaned_data.get('Location')
        location = geolocator.geocode(locat)
        # print(location)
        l_lat = location.latitude
        l_long = location.longitude
        pointa = (l_lat, l_long)

        map = folium.Map(location=(l_lat, l_long))
        folium.Marker(
            location=[l_lat, l_long],
            raduis=5,
            tooltip=
            f"{city['city']}, {city['region']}, {city['country_name']}, {city['country_code']}",
            icon=folium.Icon(color="red")).add_to(map)
        folium.TileLayer('Mapbox Control Room').add_to(map)
        folium.TileLayer('Stamen Toner').add_to(map)
        folium.TileLayer('Stamen Terrain').add_to(map)
        folium.TileLayer('Stamen Watercolor').add_to(map)
        folium.TileLayer('CartoDB positron').add_to(map)
        folium.TileLayer('CartoDB dark_matter').add_to(map)

        # print("##",location)

        dest = form.cleaned_data.get('Destination')
        destination = geolocator.geocode(dest)
        # print("Destination",destination)
        if destination == None:
            messages.error(request,
                           "Check the Destination Location then Try Again")
        else:

            d_lat = destination.latitude
            d_lon = destination.longitude
            pointb = (d_lat, d_lon)
            distance = round(geodesic(pointa, pointb).km, 2)

            map = folium.Map(location=cords(l_lat, l_long, d_lat, d_lon),
                             zoom_start=zooming(distance))

            folium.Marker(
                location=[l_lat, l_long],
                raduis=5,
                tooltip=
                f"{city['city']}, {city['region']}, {city['country_name']}, {city['country_code']}",
                icon=folium.Icon(color="red")).add_to(map)
            folium.Marker(location=[d_lat, d_lon],
                          raduis=5,
                          tooltip=dest,
                          icon=folium.Icon(color="blue")).add_to(map)
            folium.TileLayer('Mapbox Control Room').add_to(map)
            folium.TileLayer('Stamen Toner').add_to(map)
            folium.TileLayer('Stamen Terrain').add_to(map)
            folium.TileLayer('Stamen Watercolor').add_to(map)
            folium.TileLayer('CartoDB positron').add_to(map)
            folium.TileLayer('CartoDB dark_matter').add_to(map)

            folium.PolyLine(locations=(pointa, pointb),
                            weight=5,
                            tooltip=f"Distance is {distance}km",
                            color='blue').add_to(map)

            instance.Location = location
            instance.Distance = distance
            instance.save()

    map.add_child(folium.LayerControl())
    map = map._repr_html_()

    context = {
        # 'distane_obj':obj,
        'Distance': Mes.objects.last(),
        'form': form,
        'map': map,
    }

    return render(request, 'index.html', context)
Beispiel #24
0
for lt, ln, el in zip(lat, lon, ele):  # marker adder
    colorr = color_picker(el)
    fgv.add_child(
        folium.CircleMarker(location=[lt, ln],
                            radius=10,
                            color='grey',
                            fill_color=color_picker(el),
                            fill=True,
                            fill_opacity=0.7,
                            popup="%s m" % (el),
                            icon=folium.Icon(color=colorr,
                                             icon='hashtag',
                                             prefix='fa')))

fgp = folium.FeatureGroup(name="Population")

fgp.add_child(
    folium.GeoJson(
        data=open('world.json', 'r', encoding='utf-8-sig').read(),
        style_function=lambda x: {
            'fillColor':
            'green' if x['properties']['POP2005'] < 10000000 else 'orange'
            if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red'
        }))  # Data from the world json and use the style function

map1.add_child(fgv)
map1.add_child(fgp)
map1.add_child(folium.LayerControl())  # Looks for childs
map1.save("map1.html")
Beispiel #25
0
# for row in state_data :


m = folium.Map(location=[36, 127], tiles="OpenStreetMap", zoom_start=7)
# folium.Map(location=[37.566345, 126.977893], zoom_start=17, tiles='Stamen Terrain')
# folium.Map(location=[37.566345, 126.977893], zoom_start=17, tiles='Stamen Toner')

# folium.Marker([37.566345, 126.977893], popup='서울특별시청').add_to(map_osm)
# folium.Marker([37.5658859, 126.9754788], popup='덕수궁').add_to(map_osm)

# folium.Marker([37.566345, 126.977893], popup='서울특별시청', icon=folium.Icon(color='red',icon='info-sign')).add_to(map_osm)
# folium.CircleMarker([37.5658859, 126.9754788], radius=100,color='#3186cc',fill_color='#3186cc', popup='덕수궁').add_to(map_osm)

m.choropleth(
    geo_data=state_geo,
    name='choropleth',
    data=state_data,
    columns=['Code', 'Population'],
    key_on='feature.properties.CTPRVN_CD',
    fill_color='PuRd',
    fill_opacity=0.7,
    line_opacity=0.5,
    legend_name='Population Rate (%)'
)

folium.LayerControl().add_to(m)

m.save('folium_kr.html')
webbrowser.open_new("folium_kr.html")
Beispiel #26
0
def generate_map(week, logos_enabled=True, schools_enabled=False):
    CENTER = (39.8283, -98.5795)
    DEFAULT_ZOOM = 4
    geojson_filename = dir / "json" / str(year) / "week{}.json".format(week)

    map = folium.Map(location=CENTER,
                     tiles='CartoDB positron',
                     zoom_start=DEFAULT_ZOOM)

    def style(feature):
        return {
            'fillOpacity': .85,
            'fillColor': feature['color'],
            'weight': 0.75,
            'color': 'black'
        }

    def draw_counties(geojson_filename):
        folium.GeoJson(data=str(geojson_filename),
                       name='geojson',
                       style_function=style).add_to(map)

    def draw_schools():
        for i in range(len(schools.values)):
            popup = folium.Popup(schools['School'][i], parse_html=True)
            location = [schools['Lat'][i], schools['Long'][i]]
            folium.Marker(location, popup=popup).add_to(map)

    def draw_logos():
        clusters = find_clusters()
        for i in range(len(clusters)):
            location = [clusters['Lat'][i], clusters['Long'][i]]
            icon = folium.features.CustomIcon(icon_image=clusters['Logo'][i],
                                              icon_size=(35, 35),
                                              icon_anchor=None)
            folium.Marker(location=location,
                          tooltip=clusters['School'][i],
                          icon=icon).add_to(map)

    def find_clusters():
        school_clusters = []
        school_names = []
        logos = []
        for i in range(len(school_centroids)):
            k = schools['K'][i]
            if k != 0:
                cluster, _ = kmeans(school_centroids[i], k)
                for j in range(len(cluster)):
                    school_clusters.append(cluster[j])
                    school_names.append(schools['School'][i])
                    logos.append(schools['Logo'][i])
        school_clusters = np.array(school_clusters)
        return pd.DataFrame({
            "Lat": school_clusters[:, 0],
            "Long": school_clusters[:, 1],
            "School": school_names,
            "Logo": logos
        })

    draw_counties(dir / "json" / str(year) / "week{}.json".format(week))
    folium.LayerControl().add_to(map)
    if (logos_enabled):
        draw_logos()
    if (schools_enabled):
        draw_schools()
    map.save(
        str(dir / "output_maps" / str(year) / "map_week{}.html".format(week)))
Beispiel #27
0
elev = list(data["ELEV"])

#return a different color for markers based on height

def color_producer(elevation):
    if elevation<1000:
        return 'green'
    elif elevation>=1000 and el<3000:
        return 'orange'
    else:
        return 'red'


map =folium.Map(location = [38.2,-99.1],zoom_start=5,tiles="Mapbox Bright")
fgv = folium.FeatureGroup(name="Volcanoes")
for lt,ln,el in zip(lat,lon,elev):

    fgv.add_child(folium.CircleMarker(location=[lt,ln], radius=5, popup = str(el) + " m",
    color='grey',fill_color=color_producer(el)))

fgp = folium.FeatureGroup(name="Population")

fgp.add_child(folium.GeoJson(data=open('world.json', 'r', encoding='utf-8-sig'),
style_function=lambda x: {'fillColor':'green' if x['properties']['POP2005'] < 10000000
else 'orange' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red'}))

map.add_child(fgp)#each feature group object is a layer,fgv has all volcano objects and fgp with population ones
map.add_child(fgv)
map.add_child(folium.LayerControl())#refers to the fgv and fgp layers which are added to map each layers refers to the name mentioned when initializing it
map.save("Map1.html")
Beispiel #28
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')
Beispiel #29
0
import folium
import pandas

data = pandas.read_csv("Volcanoes.txt")
lat = list(data["LAT"])
lon = list(data["LON"])
elev = list(data["ELEV"])


def color_producer(elevation):
    if ele<=2000:
        return 'green'
    elif ele>2000 and ele<=3000:
        return 'orange'
    else:
        return 'red'

map = folium.Map(location=[38.58, -99.09],zoom_start =6)

fg = folium.FeatureGroup(name = "MyMap")

for lt, ln, ele in zip(lat,lon,elev):
        fg.add_child(folium.CircleMarker(location=[lt, ln], popup=str(ele)+"m", fill_color = color_producer(ele), color = 'grey', fill_opacity =0.7))

fg.add_child(folium.GeoJson(data = open('world.json','r',encoding = 'utf-8-sig').read(), style_function = lambda x:{'fillColor':'yellow'}))
map.add_child(fg)
map.add_child(folium.LayerControl())

map.save("Map1.html")
Beispiel #30
0
    def _map_images(
        plot_file_format: List[str],
        result_df: GeoDataFrame,
        filepaths: List[Union[str, Path]],
        aoi: GeoDataFrame = None,
        show_images=True,
        show_features=False,
        name_column: str = "id",
        save_html: Path = None,
    ) -> folium.Map:
        """
        Displays data.json, and if available, one or multiple results geotiffs.
        Args:
            plot_file_format: List of accepted image file formats e.g. [".png"]
            result_df: GeoDataFrame with scene geometries.
            aoi: GeoDataFrame of aoi.
            filepaths: Paths to images to plot. Optional, by default picks up the last
                downloaded results.
            show_images: Shows images if True (default).
            show_features: Show features if True. For quicklooks maps is set to False.
            name_column: Name of the feature property that provides the Feature/Layer name.
            save_html: The path for saving folium map as html file. With default None, no file is saved.
        """
        if result_df.shape[0] > 100:
            result_df = result_df.iloc[:100]
            logger.info(
                "Only the first 100 results will be displayed to avoid memory "
                "issues.")

        centroid = box(*result_df.total_bounds).centroid
        m = folium_base_map(
            lat=centroid.y,
            lon=centroid.x,
        )

        df_bounds = result_df.bounds
        list_bounds = df_bounds.values.tolist()
        raster_filepaths = [
            path for path in filepaths if Path(path).suffix in plot_file_format
        ]

        try:
            feature_names = result_df[name_column].to_list()
        except KeyError:
            feature_names = [""] * len(result_df.index)

        if aoi is not None:
            aoi_style = VECTOR_STYLE.copy()
            aoi_style["color"] = "red"
            folium.GeoJson(
                aoi,
                name="aoi",
                style_function=lambda x: aoi_style,
                highlight_function=lambda x: HIGHLIGHT_STYLE,
            ).add_to(m)

        if show_features:
            for idx, row in result_df.iterrows():  # type: ignore
                try:
                    feature_name = row.loc[name_column]
                except KeyError:
                    feature_name = ""
                layer_name = f"Feature {idx + 1} - {feature_name}"
                f = folium.GeoJson(
                    row["geometry"],
                    name=layer_name,
                    style_function=lambda x: VECTOR_STYLE,
                    highlight_function=lambda x: HIGHLIGHT_STYLE,
                )
                folium.Popup(
                    f"{layer_name}: {row.drop('geometry', axis=0).to_json()}"
                ).add_to(f)
                f.add_to(m)

        if show_images and raster_filepaths:
            for idx, (raster_fp, feature_name) in enumerate(
                    zip(raster_filepaths, feature_names)):
                with rasterio.open(raster_fp) as src:
                    if src.meta["crs"] is None:
                        dst_array = src.read()[:3, :, :]
                        minx, miny, maxx, maxy = list_bounds[idx]
                    else:
                        # Folium requires 4326, streaming blocks are 3857
                        with WarpedVRT(src, crs="EPSG:4326") as vrt:
                            dst_array = vrt.read()[:3, :, :]
                            minx, miny, maxx, maxy = vrt.bounds

                m.add_child(
                    folium.raster_layers.ImageOverlay(
                        np.moveaxis(np.stack(dst_array), 0, 2),
                        bounds=[[miny, minx], [maxy,
                                               maxx]],  # different order.
                        name=f"Image {idx + 1} - {feature_name}",
                    ))

        # Collapse layer control with too many features.
        collapsed = bool(result_df.shape[0] > 4)
        folium.LayerControl(position="bottomleft",
                            collapsed=collapsed).add_to(m)

        if save_html:
            save_html = Path(save_html)
            if not save_html.exists():
                save_html.mkdir(parents=True, exist_ok=True)
            filepath = save_html / "final_map.html"
            with filepath.open("w") as f:
                f.write(m._repr_html_())
        return m