コード例 #1
0
ファイル: views.py プロジェクト: Shovon588/corona-info
def map_view(request):
    districts = DistrictInfo.objects.all()
    bd_lat = 23.6850
    bd_lon = 90.3563

    figure = folium.Figure()
    m = folium.Map(location=[bd_lat, bd_lon], zoom_start=8)
    m.add_to(figure)

    for dist in districts:
        info = CaseInfo.objects.filter(name=dist).order_by('-date')
        folium.vector_layers.CircleMarker(
            location=[dist.lat, dist.lon],
            radius=np.log(
                info[0].cases *
                300),  # define how big you want the circle markers to be
            color=None,
            fill=True,
            tooltip=dist.dist_name + ": " + str(info[0].cases),
            fill_color='red',
            fill_opacity=0.7).add_to(m)

    figure.render()
    updated = info[0].date

    return render(request, 'map.html', {'map': figure, 'updated': updated})
コード例 #2
0
def run():
    country_geo = 'world-countries.json'

    mapa = folium.Figure(width=1000, height=500)
    mapp = folium.Map(location=[20, 0], zoom_start=1.5).add_to(mapa)

    result['name'] = result[' Country']
    data_to_plot = result[['name', ' Cumulative_cases']]

    choropleth = (folium.Choropleth(
        geo_data=country_geo,
        data=data_to_plot,
        columns=['name', ' Cumulative_cases'],
        key_on='properties.name',
        fill_color='YlGnBu',
        fill_opacity=0.7,
        line_opacity=0.2,
        legend_name="Covid incidence in individual countries",
        highlight=True)).add_to(mapp)

    choropleth.geojson.add_child(
        folium.features.GeoJsonTooltip(['name'], labels=False))

    WIDTH = 700
    HEIGHT = 700

    div = Div(text=mapa._repr_html_(), width=WIDTH, height=HEIGHT)

    return row(div)
コード例 #3
0
    def get_context_data(self, **kwargs):
        figure = folium.Figure()
        m = folium.Map(
            location=[48.88161719999999, 2.3033608],
            zoom_start=10,

        )
        m.add_to(figure)
        utilisateurs = Utilisateur.objects.all()
        for utilisateur in utilisateurs:
            adresse = utilisateur.adresse
            coordonnees = [adresse.latitude, adresse.longitude]
            nombredecommande = Commande.objects.filter(user=utilisateur.user).count()
            if nombredecommande >= 10:
                color = "red"
            elif nombredecommande >= 2:
                color = "orange"
            else:
                color = "green"

            folium.Marker(
                location=coordonnees,
                popup=utilisateur.user.first_name,
                icon=folium.Icon(icon='user', color=color)

            ).add_to(m)

        figure.render()
        return {"map": figure}
コード例 #4
0
    def get_figure(self, area):
        center = [37.541, 126.986]
        m = folium.Map(location=center, zoom_start=10)

        if area is None or area == '동':
            folium.Choropleth(
                geo_data=self.geo_data,
                data=self.df,
                columns=('동', '인구'),
                key_on='feature.properties.동',
                fill_color='BuPu',
                legend_name='노령 인구수',
            ).add_to(m)
        else:
            df_adm = self.df.groupby(['구'])(['인구']).to_frame().reset_index()

            folium.Choropleth(
                geo_data=self.geo_data,
                data=df_adm,
                columns=('구', '인구'),
                key_on='feature.properties.구',
                fill_color='BuPu',
                legend_name='노령 인구수',
            ).add_to(m)

        figure = folium.Figure()
        m.add_to(figure)
        figure.render()

        return figure
コード例 #5
0
ファイル: test_features.py プロジェクト: zoeyherm/folium
def test_figure_rendering():
    f = folium.Figure()
    out = f.render()
    assert type(out) is str

    bounds = f.get_bounds()
    assert bounds == [[None, None], [None, None]], bounds
コード例 #6
0
def folium_static(fig, width=700, height=500):
    """
    Renders `folium.Figure` or `folium.Map` in a Streamlit app. This method is 
    a static Streamlit Component, meaning, no information is passed back from
    Leaflet on browser interaction.

    Source: https://github.com/randyzwitch/streamlit-folium/blob/master/streamlit_folium/__init__.py
    # NOTE: reproduced in order to be able to use it without installing the component.
    Parameters
    ----------
    width : int
        Width of result
    
    Height : int
        Height of result
    Note
    ----
    If `height` is set on a `folium.Map` or `folium.Figure` object, 
    that value supersedes the values set with the keyword arguments of this function. 
    Example
    -------
    >>> m = folium.Map(location=[45.5236, -122.6750])
    >>> folium_static(m)
    """

    # if Map, wrap in Figure
    if isinstance(fig, folium.Map):
        fig = folium.Figure().add_child(fig)

    return components.html(fig.render(),
                           height=(fig.height or height) + 10,
                           width=width)
コード例 #7
0
ファイル: base.py プロジェクト: aidowu/Route_Dynamics
def route_map(gdf_route):
    """
       Creates interactive map for the desired route.
       
       Parameters
       ----------
       gdf_route: geodataframe output from make_multi_lines()
       
       Returns
       -------
       route_map: interactive map that displays the desired route and road grade
    """
    UW_coords = [47.655548, -122.303200]
    figure_size = folium.Figure(height = 400)
    route_map = folium.Map(location = UW_coords, zoom_start = 12)
    min_grade = min(gdf_route['gradient'])
    max_grade = max(gdf_route['gradient'])
    route_json = gdf_route.to_json()
    linear_map = cm.linear.Paired_06.scale(min_grade, max_grade )
    route_layer = folium.GeoJson(route_json, style_function = lambda feature: {
        'color': linear_map(feature['properties']['gradient']),
        'weight': 8})
    route_layer.add_child
    route_map.add_child(linear_map)
    route_map.add_child(route_layer)
    route_map.add_to(figure_size)
    return route_map
コード例 #8
0
ファイル: test_features.py プロジェクト: zoeyherm/folium
def test_figure_double_rendering():
    f = folium.Figure()
    out = f.render()
    out2 = f.render()
    assert out == out2

    bounds = f.get_bounds()
    assert bounds == [[None, None], [None, None]], bounds
コード例 #9
0
def test_figure_html():
    f = folium.Figure()
    out = f.render()
    out = os.linesep.join([s.strip() for s in out.splitlines() if s.strip()])
    assert out.strip() == tmpl.strip(), '\n' + out.strip() + '\n' + '-' * 80 + '\n' + tmpl.strip()  # noqa

    bounds = f.get_bounds()
    assert bounds == [[None, None], [None, None]], bounds
コード例 #10
0
    def createNewMap(lat=32.02677, lon=34.74283):
        # initate map
        latlng = [lat, lon]
        zoom = 20
        f = folium.Figure(width=1000, height=1000)
        fmap = folium.Map(latlng, zoom_start=zoom,
                          tiles='cartodbpositron').add_to(f)

        return (fmap)
コード例 #11
0
def visualize_airport_map(df, zoom):
    lat_map = 30.038557
    lon_map = 31.231781
    
    f = folium.Figure(width=1000, height=500)
    m = folium.Map([lat_map, lon_map], zoom_start=zoom).add_to(f)
    
    for i in range(0, len(df)):
        folium.Marker(location=[df["lat"][i], df["long"][i]], icon=folium.Icon(icon_color ="Red", icon="plane", prefix="fa")).add_to(m)
        
        return m
コード例 #12
0
def create_map(table, zips, mapped_feature, add_text=''):
    # reading of the updated GeoJSON file
    nyc_geo = r'data/nyc_updated-file.json'
    # initiating a Folium map with NYC's longitude and latitude 40.7128° N, 74.0060° W
    f = folium.Figure(width=1000, height=1000)
    m = folium.Map(location=[40.7128, -74.0060],
                   zoom_start=10,
                   width=500,
                   height=500).add_to(f)
    # creating a choropleth map
    m.choropleth(
        geo_data=nyc_geo,
        fill_color='YlGn',
        fill_opacity=0.6,
        line_opacity=0.8,
        data=table,
        # refers to which key within the GeoJSON to map the ZIP code to
        key_on='feature.properties.zcta',
        # first element contains location information, second element contains feature of interest
        columns=[zips, mapped_feature],
        legend_name=(' ').join(mapped_feature.split('_')).title() + ' ' +
        add_text + ' Across NYC')
    folium.LayerControl().add_to(m)
    print(mapped_feature)
    # save map with filename based on the feature of interest
    #     m.save(outfile = mapped_feature + '_map.html')
    m.save(outfile='html/imap.html')
    return m


# def modify_doc(doc):

#     select = Select(title='Demographic attribute', value='median_employee_salary', options=menu_list, width =500)
#     div=Div(text="<iframe src="r'imap.html'" style='min-width:calc(100vw - 26px); height: 500px'><iframe>", width=500)

#     def update_attribute(attrname, old, new):
#         attribute = select.value
#         demog_m=create_map(df_demo_join_cherre, 'zip', attribute, 'per Zipcode')

#         div.text=demog_m._repr_html_()

#         return div

#     select.on_change('value', update_attribute)

#     layout = column(row(select), row(div))

#     doc.add_root(layout)

# # show(modify_doc, notebook_url="localhost:8890")
コード例 #13
0
def Mapping():
    global fig

    with app.app_context():
        count = db.session.query(Data.name_).count()

        fig = folium.Figure(width=1000, height=200)
        map = folium.Map(location=[33.811257, 35.605018],
                         zoom_start=14,
                         tiles='OpenStreetMap')
        org = folium.FeatureGroup(name="Green")
        carbsour = folium.FeatureGroup(name="Brown")

        for i in range(count):

            name = db.session.query(Data.name_)[i][0]
            coord = db.session.query(Data.coord_)[i][0].split(",")

            try:

                lat = float(coord[0])
                lon = float(coord[1])
                res = db.session.query(Data.source_)[i][0]

                if res == "Brown":
                    html = '<p>Resource : Brown</p>'
                    test = folium.Html("Name: " + name + html, script=True)
                    popup = folium.Popup(test)

                    carbsour.add_child(
                        folium.Marker(location=[lat, lon],
                                      popup=popup,
                                      icon=folium.Icon(color='darkred')))

                elif res == "Green":
                    html = '<p>Resource : Green</p>'
                    test = folium.Html("Name: " + name + html, script=True)
                    popup = folium.Popup(test)
                    popup = folium.Popup(test, max_width=400)
                    org.add_child(
                        folium.Marker(location=[lat, lon],
                                      popup=popup,
                                      icon=folium.Icon(color='green')))
            except:
                message_coord = "Warning: Coordinates are not numerical values"
        map.add_child(org)
        map.add_child(carbsour)
        map.add_child(folium.LayerControl())
        fig.add_child(map)
コード例 #14
0
ファイル: viztools.py プロジェクト: shahin-jafarzadeh/up42-py
def folium_base_map(
    lat: float = 52.49190032214706,
    lon: float = 13.39117252959244,
    zoom_start: int = 14,
    width_percent: str = "95%",
    layer_control=False,
) -> folium.Map:
    """Provides a folium map with basic features and UP42 logo."""
    mapfigure = folium.Figure(width=width_percent)
    m = folium.Map(location=[lat, lon], zoom_start=zoom_start,
                   crs="EPSG3857").add_to(mapfigure)

    tiles = (
        "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery"
        "/MapServer/tile/{z}/{y}/{x}.png")
    attr = ("Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, "
            "AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the "
            "GIS User Community")
    folium.TileLayer(tiles=tiles, attr=attr, name="Satellite - ESRI").add_to(m)

    formatter = "function(num) {return L.Util.formatNum(num, 4) + ' ';};"
    folium.plugins.MousePosition(
        position="bottomright",
        separator=" | ",
        empty_string="NaN",
        lng_first=True,
        num_digits=20,
        prefix="lon/lat:",
        lat_formatter=formatter,
        lng_formatter=formatter,
    ).add_to(m)

    folium.plugins.MiniMap(tile_layer="OpenStreetMap",
                           position="bottomright",
                           zoom_level_offset=-6).add_to(m)
    folium.plugins.Fullscreen().add_to(m)
    folium.plugins.FloatImage(
        image=
        "https://cdn-images-1.medium.com/max/140/1*[email protected]",
        bottom=90,
        left=88,
    ).add_to(m)

    if layer_control:
        folium.LayerControl(position="bottomleft", collapsed=False,
                            zindex=100).add_to(m)
        # If adding additional layers outside of the folium base map function, don't
        # use this one here. Causes an empty map.
    return m
コード例 #15
0
ファイル: fonctions.py プロジェクト: RemiEC/Python-projet
def Creation(request):
    erreur = ""
    global id_utilisateur
    global nb_personne_foyer
    global FormCreation
    fig = folium.Figure(width=750, height=600)
    m = folium.Map(location=[48.8534, 2.3488],
                   tiles='OpenStreetMap',
                   zoom_start=10).add_to(fig)

    if (request.method != 'POST'):
        FormCreation = form.CreationForm()
    if (request.method == 'POST'):
        if (request.POST.get('creation')):
            FormCreation = form.CreationForm(request.POST)
            if (FormCreation.is_valid()):
                data = FormCreation.cleaned_data
                print("data", data)
                #Vérifier unicité
                if (methodes_JSON.VerifUniciteClient(data['id_box'],
                                                     data['latitude'],
                                                     data['longitude'])):
                    #* Mettre les DATA dans le JSON
                    methodes_JSON.EnregistrerClient(data)
                    id_utilisateur = data['id_box']
                    nb_personne_foyer = data['nb_foyer']
                    return redirect('Page_Detail')
                erreur = "Doublon d'un compte existant ou id déjà utilisé"
        if (request.POST.get('bouton')):
            FormCreation = form.CreationForm(request.POST)
            if (FormCreation.is_valid()):
                data = FormCreation.cleaned_data
                longitude = data['longitude']
                latitude = data['latitude']
                m = folium.Map(location=[latitude, longitude],
                               width=750,
                               height=500,
                               zoom_start=20)
                tooltip = 'Click me!'
                folium.Marker([latitude, longitude],
                              popup='<i>Votre domicile</i>',
                              tooltip=tooltip).add_to(m)
    m = m._repr_html_()

    return render(request, 'HTML/creation_compte.html', {
        'erreur': erreur,
        'Form_Creation': FormCreation,
        'map': m
    })
コード例 #16
0
def interactive_facilities_map(facilities_nm):
    facilities = gpd.read_file(facilities_nm)
    facilities = add_facilities_icon(facilities)
    
    map_center = get_map_center(facilities)
    maploc = folium.Map(location=map_center, zoom_start=6, prefer_canvas=True, tiles="Stamen Terrain")
    marker_cluster = MarkerCluster().add_to(maploc)

    facility_locations = facilities[['FacilityLatitude', 'FacilityLongitude']]
    fclty_pnts = facility_locations.values.tolist()

    for fc_pnt in range(0, len(fclty_pnts)):
        f = folium.Figure()

        # add campsite mini map into popup window (due to high load times, this feature was removed)
        # facility_id = facilities['FacilityID'][fc_pnt]
        # campsite_map = interactive_campsite_map(campsite_nm, facility_id)
        # campsite_map.add_to(f)

        facility_popup_info = f"___________________________________________________________________________________________ <br> \
                                            <b style='color:Tomato;'>Facility Name:</b> {facilities['FacilityName'][fc_pnt]} <br><br> \
                                                    <b style='color:Tomato;'>Facility ID:</b>  {facilities['FacilityID'][fc_pnt]} <br><br> \
                                                        <b style='color:Tomato;'>Facility Type:</b>  {facilities['FacilityTypeDescription'][fc_pnt]} <br><br> \
                                                            <b style='color:Tomato;'> Total Campsites:</b>  {facilities['TotalCampsites'][fc_pnt]} <br><br> \
                                                                <b style='color:Tomato;'>Reservable:</b> {facilities['Reservable'][fc_pnt]} <br><br> \
                                                                    {facilities['FacilityDescription'][fc_pnt]} <br><br>\
                                                                ___________________________________________________________________________________________ <br>"
        iframe = folium.IFrame(html=facility_popup_info, width=500, height=300)
        f.add_to(iframe)
        popup = folium.Popup(iframe, max_width=2650)

        facility_icon = folium.Icon(color = 'green')#icon= facilities['FacilityTypeIcon'][fc_pnt], icon='map-pin', prefix='fa')          
        folium.Marker(fclty_pnts[fc_pnt], popup= popup, icon = facility_icon, tooltip=facilities['FacilityName'][fc_pnt]).add_to(marker_cluster)
    
    plugins.Fullscreen(
        position="topright",
        title="Expand me",
        title_cancel="Exit me",
        force_separate_button=True,
    ).add_to(maploc)

    minimap = plugins.MiniMap()
    maploc.add_child(minimap)
    plugins.Geocoder().add_to(maploc)

    maploc.save("../docs/facility_map.html")
    return maploc
コード例 #17
0
def get_map(search_key):
    lat = df.loc[df['address'] == search_key, 'latitude'].iloc[0]
    lon = df.loc[df['address'] == search_key, 'longitude'].iloc[0]
    f = folium.Figure(height=600)
    m = folium.Map(location=[lat, lon], tiles="cartodbpositron",
                   zoom_start=17).add_to(f)
    icon_path = r"./static/icons/billboard_icon.png"
    icon_png = folium.features.CustomIcon(icon_image=icon_path,
                                          icon_size=(50, 50))
    folium.Marker(
        [lat, lon],
        icon=icon_png,
        tooltip=search_key + " Billboard",
    ).add_to(m)
    plugins.Fullscreen().add_to(m)
    map_html = m._repr_html_()
    return map_html
コード例 #18
0
    def get_foodtruck_figure(self):
        center = [36.701553, 127.941129]

        m = folium.Map(location=center, zoom_start=7)

        for i in self.df2.index[:]:
            current_loc = self.df2.loc[i, ['위도', '경도']].dropna()
            if current_loc.size != 0:
                folium.Circle(location=(current_loc['위도'], current_loc['경도']),
                              tooltip=self.df2.loc[i, '시군구명'],
                              radius=200).add_to(m)

        figure = folium.Figure()
        m.add_to(figure)
        figure.render()

        return figure
コード例 #19
0
ファイル: views.py プロジェクト: devChann/gee_django
    def get_context_data(self, **kwargs):

        figure = folium.Figure()

        # create Folium Object
        m = folium.Map(
            location=[28.5973518, 83.54495724],
            zoom_start=8
        )

        # add map to figure
        m.add_to(figure)

        # select the Dataset Here's used the MODIS data
        dataset = (ee.ImageCollection('MODIS/006/MOD13Q1')
                   .filter(ee.Filter.date('2019-07-01', '2019-11-30'))
                   .first())
        modisndvi = dataset.select('NDVI')

        # Styling
        vis_paramsNDVI = {
            'min': 0,
            'max': 9000,
            'palette': ['FE8374', 'C0E5DE', '3A837C', '034B48', ]}

        # add the map to the the folium map
        map_id_dict = ee.Image(modisndvi).getMapId(vis_paramsNDVI)

        # GEE raster data to TileLayer
        folium.raster_layers.TileLayer(
            tiles=map_id_dict['tile_fetcher'].url_format,
            attr='Google Earth Engine',
            name='NDVI',
            overlay=True,
            control=True
        ).add_to(m)

        # add Layer control
        m.add_child(folium.LayerControl())

        # figure
        figure.render()

        # return map
        return {"map": figure}
コード例 #20
0
    def get_context_data(self, **kwargs):

        figure = folium.Figure()

        m = folium.Map(
            location=[28.5973518, 83.54495724],
            zoom_start=8,
        )
        m.add_to(figure)

        dataset = ee.ImageCollection('MODIS/006/MOD13Q1').filter(
            ee.Filter.date('2019-07-01', '2019-11-30')).first()
        modisndvi = dataset.select('NDVI')
        visParams = {
            'min': 0,
            'max': 3000,
            'palette': ['225ea8', '41b6c4', 'a1dab4', '034B48']
        }
        vis_paramsNDVI = {
            'min': 0,
            'max': 9000,
            'palette': [
                'FE8374',
                'C0E5DE',
                '3A837C',
                '034B48',
            ]
        }

        map_id_dict = ee.Image(modisndvi).getMapId(vis_paramsNDVI)
        folium.raster_layers.TileLayer(
            tiles=map_id_dict['tile_fetcher'].url_format,
            attr='Google Earth Engine',
            name='NDVI',
            overlay=True,
            control=True).add_to(m)

        m.add_child(folium.LayerControl())

        figure.render()

        print('test')
        return {"map": figure}
コード例 #21
0
def get_coordinates(keyword):
    objid = df.loc[df["WARD_NAME"] == str(keyword), "OBJECTID"].iloc[0]
    for i in range(len(geojsonData["features"])):
        if (geojsonData["features"][i]["properties"]["OBJECTID"] == objid):
            area_co = geojsonData["features"][i]
            strt_co = geojsonData["features"][i]["geometry"]["coordinates"][0][
                0][0]
    f = folium.Figure(height=350)
    m = folium.Map(
        location=[strt_co[1], strt_co[0]],
        tiles="cartodbpositron",
        zoom_start=13,
    ).add_to(f)
    folium.GeoJson(area_co,
                   name='geojson',
                   tooltip="<b>{}</b>".format(keyword)).add_to(m)
    plugins.Fullscreen().add_to(m)
    map_html = m._repr_html_()
    return map_html
コード例 #22
0
def route_map(shapefile, route, rasterfile):
    line = make_multi_lines(shapefile, route, rasterfile)
    UW_coords = [47.6, -122.3]
    figure_size = folium.Figure(height = 400)
    route_map = folium.Map(location = UW_coords, zoom_start = 12)
    
    min_grade = min(line['gradient'])
    max_grade = max(line['gradient'])
    linear_map = cm.linear.RdYlBu_04.scale(min_grade, max_grade )
        
    route_layer = folium.GeoJson(line.to_json(), style_function = lambda feature: {
        'color': linear_map(feature['properties']['gradient']),
        'weight': 8})
    
    route_map.add_child(linear_map)
    route_map.add_child(route_layer)
    route_map.add_to(figure_size)
    
    return (route_map)
コード例 #23
0
def EntrepotArrondissementMap():
    df=pd.DataFrame({'Arrondissement':[75001,75002,75003,75004,75005,75006,75007,75008,75009,75010,75011,75012,75013,75014,75015,75016,75017,75018,75019,75020],
                      'Latitude':[48.86251,48.86649,48.863673,48.85464,48.845443,48.850697,48.858125,48.877962,48.872873,48.871734,48.858916,48.841413,48.832375,48.832741,48.842268,48.863506,48.884682,48.892182,48.888404,48.868454],
                      'Longitude':[2.337419,2.340099,2.360845,2.362531,2.343935,2.332586,2.314873,2.315784,2.339604,2.358037,2.378265,2.388038,2.352903,2.32513,2.298531,2.279297,2.315886,2.34656,2.388472,2.404612],
                      'N_tel_Entrepôt':['013075001','013075002','013075003','013075004','013075005','013075006','013075007','013075008','013075009','013075010',
                                        '013075011','013075012','013075013','013075014','013075015','013075016','013075017','0130750018','0130750019','013075020'],
                      'Adresse':['151 Rue de Rivoli, 75001 Paris, France',
                                 '1 Galerie Vivienne, 75002 Paris, France',
                                 '53 Rue de Bretagne, 75003 Paris, France',
                                 '87 Rue Saint-Antoine, 75004 Paris, France',
                                 'La Libre Pensée, Rue des Fossés Saint-Jacques, 75005 Paris, France',
                                 '78 Rue Bonaparte, 75006 Paris, France',
                                 '144 Rue de Grenelle, 75007 Paris, France',
                                 '87 Boulevard Malesherbes, 75008 Paris, France',
                                 '10 Rue Chauchat, 75009 Paris, France',
                                 '1 Rue Pierre Bullet, 75010 Paris, France',
                                 '103 Boulevard Voltaire, 75011 Paris, France',
                                 '155 Avenue Daumesnil, 75012 Paris, France',
                                 '24 Rue Abel Hovelacque, 75013 Paris, France',
                                 '165 Avenue du Maine, 75014 Paris, France',
                                 '17 Rue du Docteur Jacquemaire Clemenceau, 75015 Paris, France',
                                 '57 Avenue Georges Mandel, 75116 Paris, France',
                                 '36 - 38 Rue de Saussure, 75017 Paris, France',
                                 '68 Rue Ordener, 75018 Paris, France',
                                 '9 Rue Adolphe Mille, 75019 Paris, France',
                                 '28 Rue de la Dhuis, 75020 Paris, France']
    })

    with open('./JSON/arrondissements.geojson') as json_file:
        data_arrondissements = json.load(json_file)

    locations = df[['Latitude', 'Longitude']]
    locationlist = locations.values.tolist()
    
    fig = folium.Figure(width=750, height=600)
    map = folium.Map(location=[48.8534, 2.3488], tiles='CartoDB positron', zoom_start=12).add_to(fig)   
    
    for point in range(0, len(locationlist)):
        folium.Marker(locationlist[point], popup=df['Adresse'][point],icon=folium.Icon(icon="cloud",color="red")).add_to(map) #on peut changer l'icone, j'ai mis celui-ci pour montrer que c'était possible
    folium.GeoJson(data_arrondissements,name='geojson',style_function=lambda x:{'fillColor': 'blue', 'color': 'blue'}).add_to(map)

    return fig._repr_html_()
コード例 #24
0
def folium_pov_data(df_plus,df_minus, c_lat, c_long):
    
    f = folium.Figure(width=1000, height=1000)
    poi_map = folium.Map(location=[c_lat, c_long], zoom_start=16).add_to(f)
    
    folium.Marker(
        location=[c_lat, c_long],
        popup = (
                 'Reference Location: ' + '<br>'
                 'Latitude: '+ str(c_long) + '<br>'
                 'Longitude: ' + str(c_long) + '<br>'
                ),
        icon=folium.Icon(color="blue",icon="fa-map-pin", prefix='fa')
            ).add_to(poi_map)
    
    
    for lat, long, category, line_of_business, industry, zipcode in zip(df_plus['latitude'], df_plus['longitude'], df_plus['category'], df_plus['line_of_business'], df_plus['Industry'], df_plus['zip']):
        folium.Marker(
        location=[lat, long],
        popup = (
                 'Industry: ' + industry + '<br>'
                 'Line of business: ' + str(line_of_business)+'<br>'
                 'category: ' + str(category)+'<br>'
                 'Zipcode: ' + str(zipcode) + '<br>'
                ),
        icon=folium.Icon(color="green",icon="plus-circle", prefix='fa')
            ).add_to(poi_map)
    
    for lat, long, category, line_of_business, industry, zipcode in zip(df_minus['latitude'], df_minus['longitude'], df_minus['category'], df_minus['line_of_business'], df_minus['Industry'], df_minus['zip']):
        folium.Marker(
        location=[lat, long],
        popup = (
                 'Industry: ' + industry + '<br>'
                 'Line of business: ' + str(line_of_business)+'<br>'
                 'category: ' + str(category)+'<br>'
                 'Zipcode: ' + str(zipcode) + '<br>'
                ),
        icon=folium.Icon(color="red",icon="minus-circle", prefix='fa')
            ).add_to(poi_map)
    
    poi_map.save(outfile = 'html/i_poi_map.html')
    return poi_map
コード例 #25
0
    def get_context_data(self, **kwargs):
        figure = folium.Figure()
        m = folium.Map(location=[45.372, -121.6972],
                       zoom_start=12,
                       tiles='Stamen Terrain')
        m.add_to(figure)

        folium.Marker(location=[45.3288, -121.6625],
                      popup='Mt. Hood Meadows',
                      icon=folium.Icon(icon='cloud')).add_to(m)

        folium.Marker(location=[45.3311, -121.7113],
                      popup='Timberline Lodge',
                      icon=folium.Icon(color='green')).add_to(m)

        folium.Marker(location=[45.3300, -121.6823],
                      popup='Some Other Location',
                      icon=folium.Icon(color='red',
                                       icon='info-sign')).add_to(m)
        figure.render()
        return {"map": figure}
def createMapToHtml(df):
    longitude = []
    latitude = []
    t = 115
    country_daily_vaccination = country_daily_vaccinations(df)
    for i in (country_daily_vaccination["country"]):
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        if findGeoCord(i) != None:
            loc = findGeoCord(i)
            longitude.append(loc.longitude)
            latitude.append(loc.latitude)
            print('le temps reste pour créer la map', timer, end="\r")
            t -= 1

        else:
            longitude.append(np.nan)
            latitude.append(np.nan)
    country_daily_vaccination['Longitude'] = longitude
    country_daily_vaccination['Latitude'] = latitude
    f = folium.Figure(width=1000, height=500)
    map = folium.Map(tiles="cartodbpositron", max_bounds=True,
                     min_zoom=1.5).add_to(f)
    marker_cluster = MarkerCluster().add_to(map)
    for i in range(len(country_daily_vaccination)):
        lon = country_daily_vaccination.iloc[i]['Longitude']
        lat = country_daily_vaccination.iloc[i]['Latitude']
        radius = 5
        popup_text = """Country : {}<br> nombre total de vaccinations par jour {}<br>"""
        popup_text = popup_text.format(
            country_daily_vaccination.iloc[i]['country'],
            country_daily_vaccination.iloc[i]['daily_vaccinations'])
        folium.CircleMarker(location=[lat, lon],
                            radius=radius,
                            popup=popup_text,
                            fill=True).add_to(marker_cluster)
    map.save('analyse/Map.html')
    print(
        'Fin !, la map.html est créée vous y trouverez dans le dossier analyse '
    )
コード例 #27
0
def makeHeatmap(request, myRadius=15, myOpacity=0.8):
    latitude = list(Accident.objects.values_list("latitude", flat=True))
    longitude = list(Accident.objects.values_list("longitude", flat=True))
    f = folium.Figure()
    m = folium.Map(location=[28.5, 2],
                   zoom_start=5,
                   tiles=tilesServer,
                   attr="openmaptiles-server")
    m.add_child(fullscreen)
    att = zip(latitude, longitude)
    if request.method == 'POST':
        form = kdeform(request.POST)
    else:
        form = kdeform()
    myRadius = request.POST.get('myRadius')
    # print((myRadius))
    myOpacity = request.POST.get('myOpacity')
    # print(type(myOpacity))
    if (myRadius == None):
        colormap = branca.colormap.LinearColormap(
            colors=['blue', 'lime', 'yellow', 'red'], vmin=0, vmax=0.8)
        colormap.add_to(m)  # add color bar at the top of the map
        m.add_child(plugins.HeatMap(att, radius=15, min_opacity=0.8))

    else:
        colormap = branca.colormap.LinearColormap(
            colors=['blue', 'lime', 'yellow', 'red'],
            vmin=0,
            vmax=float(myOpacity))
        colormap.add_to(m)  # add color bar at the top of the map
        HeatMap(att, radius=float(myRadius),
                min_opacity=float(myOpacity)).add_to(
                    folium.FeatureGroup(name='HeatMap').add_to(m))
        folium.LayerControl().add_to(m)

        # m.add_child(plugins.HeatMap(att, radius=myRadius, min_opacity=myOpacity))
    m.add_to(f)
    m = f._repr_html_()  # updated
    context = {'my_map': m, 'form': form}
    return render(request, "home/heatmap.htm", context)
コード例 #28
0
def folium_base_map(
    lat: float = 52.49190032214706,
    lon: float = 13.39117252959244,
    zoom_start: int = 5,
    width_percent: str = "95%",
    layer_control=False,
) -> folium.Map:
    """Provides a folium map with basic features."""
    mapfigure = folium.Figure(width=width_percent)
    m = folium.Map(location=[lat, lon], zoom_start=zoom_start,
                   crs="EPSG3857").add_to(mapfigure)

    folium.TileLayer(tiles="OpenStreetMap",
                     attr="OpenStreetMap",
                     name="Satellite - ESRI").add_to(m)

    formatter = "function(num) {return L.Util.formatNum(num, 4) + ' ';};"
    folium.plugins.MousePosition(
        position="bottomright",
        separator=" | ",
        empty_string="NaN",
        lng_first=True,
        num_digits=20,
        prefix="lon/lat:",
        lat_formatter=formatter,
        lng_formatter=formatter,
    ).add_to(m)

    folium.plugins.MiniMap(tile_layer="OpenStreetMap",
                           position="bottomright",
                           zoom_level_offset=-6).add_to(m)
    folium.plugins.Fullscreen().add_to(m)

    if layer_control:
        folium.LayerControl(position="bottomleft", collapsed=False,
                            zindex=100).add_to(m)
        # If adding additional layers outside of the folium base map function, don't
        # use this one here. Causes an empty map.
    return m
コード例 #29
0
def plot_avg_price_on_map(df):
    df['lat'] = [round(x, 2) for x in df['lat']]
    df['long'] = [round(x, 2) for x in df['long']]
    df = df.groupby(by=['lat', 'long'])['price'].mean().reset_index()
    print(len(df))

    map_template = folium.Map(tiles='cartodbpositron',
                              location=[47, -122],
                              zoom_start=6)

    color = list(Spectral9)
    colormap = cm.StepColormap(color,
                               vmin=df["price"].min(),
                               vmax=df["price"].max())

    diff = df["price"].max() - df["price"].min()
    range_diff = int(diff / len(color)) + 1

    for row_number, row in df.iterrows():
        n_color = int(row['price'] / range_diff)
        if n_color > 8:
            n_color = 8
        n_size = row['price'] / 1000000
        if n_size < 2:
            n_size = 1

        folium.CircleMarker([row['lat'], row['long']],
                            radius=n_size,
                            popup="average price: " + str(round(row['price'])),
                            color=color[n_color],
                            fill_color=color[n_color]).add_to(map_template)
    map_template.add_child(colormap)
    f = folium.Figure()
    string = "Average home price"
    f.html.add_child(
        folium.Element("<font face='helvetica'><font size='5'><b><p1>" +
                       string + "</b></font></p1>"))
    f.add_child(map_template)
    map_template.save('average_home_price_map.html')
コード例 #30
0
ファイル: __init__.py プロジェクト: yonglinZ/streamlit-folium
def folium_static(fig, width=700, height=500):
    """
    Renders `folium.Figure` or `folium.Map` in a Streamlit app. This method is 
    a static Streamlit Component, meaning, no information is passed back from
    Leaflet on browser interaction.

    Parameters
    ----------
    width : int
        Width of result
    
    Height : int
        Height of result

    Note
    ----
    If `height` is set on a `folium.Map` or `folium.Figure` object, 
    that value supersedes the values set with the keyword arguments of this function. 

    Example
    -------
    >>> m = folium.Map(location=[45.5236, -122.6750])
    >>> folium_static(m)

    """

    # if Map, wrap in Figure
    if isinstance(fig, folium.Map):
        fig = folium.Figure().add_child(fig)
        return components.html(fig.render(),
                               height=(fig.height or height) + 10,
                               width=width)

    # if DualMap, get HTML representation
    elif isinstance(fig, plugins.DualMap):
        return components.html(fig._repr_html_(),
                               height=height + 10,
                               width=width)