# Create custom marker icon | causes size increase of output html file 
    #meteorite_icon = folium.features.CustomIcon('Assets/meteorite.png', icon_size=(80,80))
    
    html = f"""
    <table border="1">
        <tr>
            <th> ID </th>
            <th> Name </th>
            <th> Year </th>
            <th> Mass(g) </th>
            <th> Class </th>
            <th> Latitude </th>
            <th> Longitude </th>
        </tr>
        <tr>
            <td> {ID} </td> 
            <td> {name} </td>
            <td> {year} </td>
            <td> {mass} </td>
            <td> {rec_class} </td>
            <td> {latitude} </td>
            <td> {longitude} </td>
        </tr>
    </table>"""
    iframe = folium.IFrame(html=html, width=375, height=125)
    popup = folium.Popup(iframe, max_width=375)

    folium.Marker(location=[latitude, longitude], popup=popup).add_to(cluster_map)

cluster_map.save("meteorite_cluster_map.html")
  
    This function adds layer called layer_display_name to list of layers called layers_list
    """
    layers_list.append(folium.FeatureGroup(name=layer_display_name))
    return None


def add_layers(layers_list, my_map):
    """
    (list, folium.folium.map) -> None
    This function adds all layers in layers_list list and folium.LayerControl() to map called my_map.
    """
    for layer_1 in layers_list:
        my_map.add_child(layer_1)
    my_map.add_child(folium.LayerControl())
    return None


# Creating four layers:
for text_str in [
        "First (Main) Layer", "Second Layer", "Third Layer", "Fourth Layer"
]:
    create_layer(text_str, layers_list)

layers_list[0].add_child(
    folium.Marker(location=[49, 24], popup="​1900 рік ", icon=folium.Icon()))
layers_list[1].add_child(
    folium.Marker(location=[50, 25], popup="​1902 рік ", icon=folium.Icon()))

add_layers(layers_list, my_map)

my_map.save("Map_1.html")
Exemple #3
0
# define a function to draw a basemap easily
def generateBaseMap(default_location=[47.5112, -122.257], default_zoom_start=9.4):
    base_map = folium.Map(location=default_location, control_scale=True, zoom_start=default_zoom_start)
    return base_map

df_copy = df.copy()
# select a zipcode for the heatmap
#set(df['zipcode'])
#df_copy = df[df['zipcode']==98001].copy()
df_copy['count'] = 1
basemap = generateBaseMap()
# add carton position map
folium.TileLayer('cartodbpositron').add_to(basemap)
s=folium.FeatureGroup(name='icon').add_to(basemap)
# add a marker for the house which has the highest price
folium.Marker([maxpr['lat'], maxpr['long']],popup='Highest Price: $'+str(format(maxpr['price'],'.0f')),
              icon=folium.Icon(color='green')).add_to(s)
# add heatmap
HeatMap(data=df_copy[['lat','long','count']].groupby(['lat','long']).sum().reset_index().values.tolist(),
        radius=8,max_zoom=13,name='Heat Map').add_to(basemap)
folium.LayerControl(collapsed=False).add_to(basemap)
basemap
features = ['price','bedrooms','bathrooms','sqft_living','sqft_lot','floors','waterfront',
            'view','condition','grade','sqft_above','sqft_basement','yr_built','yr_renovated',
            'zipcode','lat','long','sqft_living15','sqft_lot15']

mask = np.zeros_like(df[features].corr(), dtype=np.bool) 
mask[np.triu_indices_from(mask)] = True 

f, ax = plt.subplots(figsize=(16, 12))
plt.title('Pearson Correlation Matrix',fontsize=25)
Exemple #4
0
 def draw_on(self, folium_map):
     folium.Marker(**self._folium_kwargs).add_to(folium_map)
Exemple #5
0
    line_all.append(line_dict)

line_all_dict = {}
for line in gd:
    line_data = line.strip().split(' ')
    line_dict = {x.split(':')[0]: x.split(':')[1] for x in line_data}
    k = line_dict['城市']
    v = {'经度': line_dict['经度'], '纬度': line_dict['纬度']}
    line_all_dict.update({k: v})

print(line_all_dict['广东从化'])
print(line_all_dict['广东从化']['经度'])


def location(city):
    x = line_all_dict['广东从化']['经度']
    y = line_all_dict['广东从化']['纬度']

    return (x, y)


x, y = location('广东从化')
print(x, y)

import folium
map_osm = folium.Map(location=[x, y], zoom_start=14)
folium.Marker([x, y],
              popup="广东从化",
              icon=folium.Icon(color='red', icon='info-sign')).add_to(map_osm)
map_osm.save('map.html')
Exemple #6
0
import folium
import pandas

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

html = """<h4>Volcano information:</h4>
Height: %s m
"""

map = folium.Map(location=[48.77, -120.59], zoom_start=6)
fg = folium.FeatureGroup(name="My Map")

for lt, ln, el, name in zip(lat, lon, elev, name):
    iframe = folium.IFrame(html=html % (name, el), width=200, height=100)
    fg.add_child(
        folium.Marker(location=[lt, ln],
                      popup=folium.Popup(iframe),
                      icon=folium.Icon(color="green")))

map.add_child(fg)
map.save("Map_html_popup_advanced.html")
Exemple #7
0
        folium.Marker(
            location=[lati, logi],
            popup="""<h3 style="color:darkred"><strong>""" + name +
            """</strong></h3>""" + " " +
            """<div id="my-pics" class="carousel slide" data-ride="carousel" style="width:500px;margin:auto;">


            <ol class="carousel-indicators">
            <li data-target="#my-pics" data-slide-to="0" class="active"></li>
            <li data-target="#my-pics" data-slide-to="1"></li>
            <li data-target="#my-pics" data-slide-to="2"></li>
            </ol>


            <div class="carousel-inner" role="listbox">


            <div class="item active">
            <p>""" + description1 + """ </p>
            <img src=""" + photo1 + """>
            </div>


            <div class="item">
            <p>""" + description2 + """ </p>
            <img src=""" + photo2 + """>
            </div>


            <div class="item">
            <p>""" + description3 + """ </p>
            <img src=""" + photo3 + """>
            
            </div>

           
            </div>


            <a class="left carousel-control" href="#my-pics" role="button" data-slide="prev">
            <span class="icon-prev" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
            </a>
            <a class="right carousel-control" href="#my-pics" role="button" data-slide="next">
            <span class="icon-next" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
            </a>

            </div>""",
            icon=folium.Icon(color='darkred')))
Exemple #8
0
import folium
import pandas

data = pandas.read_csv("india.txt")
lat=list(data["LAT"])
lon=list(data["LONG"])
state=list(data["STATES"])

html = """<h4>State Information:</h4> 
Name: %s
"""

map=folium.Map(location=[20.5937, 78.9629], zoom_start=6,tiles="Mapbox Bright")
fg = folium.FeatureGroup(name="My Map")
for lt,ln,st in zip(lat,lon,state):
	iframe =  folium.IFrame(html=html % str(st), width=200, height=100)
	fg.add_child(folium.Marker(location=[lt,ln],popup=str(st), icon=folium.Icon(color="red")))

map.add_child(fg)
map.save("india.html") #an HTML file will be created in the current directory as india.html
Exemple #9
0
    def addFacts(self, array, labels, icon_map, icon_pop):
        """Creates icons on map

        Parameters
        ----------
        array : List of column name
        label : Tuple of label name
        icon_map : the icon shown on map
        icon_pop : pop up icon

        Examples
        --------
        >>> f.addFacts(['Total_mau','Other_mau', 'iOS_mau', 'Android_mau'], ('Other', 'iOS', 'Android'),'phone.png', 'myfig.png')

        """
        df = self.df
        totalname = array[0]
        array = array[1:]
        for i in range(len(array)):
            df[array[i] + totalname] = df[array[i]] / df[totalname]
        for i in range(len(array)):
            arr = [0] * len(array)
            name = array[i] + totalname
            a = df.loc[df[name].idxmax(axis=1)]
            for j in range(len(array)):
                arr[j] = a[array[j]]
            fig1, ax1 = plt.subplots(figsize=(1.8, 1.8))
            ax1.pie(arr,
                    labels=labels,
                    autopct='%1.1f%%',
                    shadow=True,
                    startangle=90)
            plt.savefig('myfig.png', transparent=True)
            html1 = '<center><img align="middle" src="data:image/png;base64,{}"></center>'
            encoded = b64encode(open(icon_pop, 'rb').read()).decode()
            encpie = b64encode(open('myfig.png', 'rb').read()).decode()
            ic = icon_map
            l = a[self.locationcol]
            latlong = a['LatLong']
            if l not in self.Loc:
                self.Loc.append(l)
                self.pdict[l], self.hdict[l], self.tdict[l], self.pidict[
                    l], self.cdict[
                        l] = '<h4><center>' + l + '</center></h4>', '', [], [], 0
                self.tdict[l].append(encoded)
                self.pdict[
                    l] += '<hr><center><p style="padding:0px 10px 0px 10px">' + l
                self.hdict[l] += html1
            self.pidict[l].append(encpie)
            self.cdict[l] += 1
            string = " highest percentage of " + labels[i] + "."
            self.pdict[
                l] += ' has the' + string + '</p></center><center><img align="middle" src="data:image/png;base64,{}"></center>'
            iframe = branca.element.IFrame(
                html=self.pdict[l].format(*self.pidict[l]),
                width=400,
                height=220 + self.cdict[l] * 50)
            folium.Marker(
                [latlong.split(",")[0],
                 latlong.split(",")[1]],
                popup=folium.Popup(iframe),
                icon=folium.features.CustomIcon(ic, icon_size=(28, 30)),
                tooltip=self.hdict[l].format(*self.tdict[l])).add_to(
                    self.basemap.feature_groups[self.feature_group][self.name])
    deces = str(ligne['Deces'])
    guerisons = str(ligne['Guerisons'])
    #for creating circle marker
    folium.CircleMarker(location=[ligne['Latitudes'], ligne['Longitudes']],
                        radius=5,
                        color='red',
                        fill=True,
                        fill_color="red").add_to(m)
    #for creating marker
    folium.Marker(
        location=[ligne['Latitudes'], ligne['Longitudes']],
        # adding information that need to be displayed on tooltip
        tooltip=ligne['Pays'],
        # adding information that need to be displayed on popup
        popup=folium.Popup(
            ('<strong><b>Pays : ' + ligne['Pays'] + '</strong> <br>' +
             '<strong><b>Infections : ' + infections + '</strong><br>' +
             '<strong><font color= red>Déces : </font>' + deces +
             '</strong><br>' +
             '<strong><font color=green>Guérisons : </font>' + guerisons +
             '</strong><br>' + '<strong><b>Taux d\'infection : ' + taux +
             '</strong>'),
            max_width=200)).add_to(m)
    m.save(outfile='Covid_01042020.html'
           )  #Le fichier de sortie est une map au format "html"
    #to show the map
    #m

# for (index,row) in df.iterrows():
#     folium.Marker(location = [row['Latitudes'], row['Longitudes']], popup = row['Noms'], tooltip = row['Adresses'], icon=folium.Icon(color = 'red', icon = 'info-sign')).add_to(m) #Inscris un marqueur aux endroits donnés avec la lontitude et lagitude
#     m.save(outfile='visualisation.html') #Le fichier de sortie est une map au format "html"
Exemple #11
0
 def addMarkers(self, points):
     for p in points:
         marcador = folium.Marker(location=(coor[1], coor[0]),
                                   icon = folium.Icon(color = "red"))
         marker.add_to(map)
                'https://www.cwb.gov.tw/V7/images/wind_icon/SSE.gif',
                'https://www.cwb.gov.tw/V7/images/wind_icon/S.gif',
                'https://www.cwb.gov.tw/V7/images/wind_icon/SSW.gif',
                'https://www.cwb.gov.tw/V7/images/wind_icon/SW.gif',
                'https://www.cwb.gov.tw/V7/images/wind_icon/WSW.gif',
                'https://www.cwb.gov.tw/V7/images/wind_icon/W.gif',
                'https://www.cwb.gov.tw/V7/images/wind_icon/WNW.gif',
                'https://www.cwb.gov.tw/V7/images/wind_icon/NW.gif',
                'https://www.cwb.gov.tw/V7/images/wind_icon/NNW.gif']

station1=folium.FeatureGroup(name="環保署",show = False)
for i in(range(16)):
    station1.add_child(
                        folium.Marker(
                                        location=[final_df['Latitude'][i],final_df['Longitude'][i]],
                                        popup=("<b>NAME:</b> {NAME}<br>""<b>PM2.5:</b> {PM25}<br>""<b>TIME:</b> {TIME}<br>")
                                                .format(NAME=str(final_df['SiteName'][i]),PM25=str(final_df['PM2.5'][i]),TIME=str(times[21:36])),
                                        icon=folium.CustomIcon(epa_icon_url,icon_size=(23,23))
                                      )
                        )

station2=folium.FeatureGroup(name="空氣盒子",show = False)
for j in range(16,70):
    station2.add_child(
                        folium.Marker(
                                        location=[final_df['Latitude'][j],final_df['Longitude'][j]],
                                        popup=("<b>NAME:</b> {NAME}<br>""<b>PM2.5:</b> {PM25}<br>""<b>TIME:</b> {TIME}<br>")
                                                .format(NAME=str(final_df['SiteName'][j]),PM25=str(final_df['PM2.5'][j]),TIME=str(times[21:36])),
                                        icon=folium.CustomIcon(airbox_icon_url,icon_size=(23,23))
                                        )
                        )
Exemple #13
0
data = pandas.read_csv("Volcanoes.txt")
lat = list(data["LAT"])
lon = list(data["LON"])
elev = list(data["ELEV"])

def color_producer(elevation):
    if elevation < 1000:
        return "green"
    elif 1000 <= elevation < 3000:
        return "orange"
    else:
        return "red"

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

fgv = folium.FeatureGroup(name = "Volcanoes")

for lt, ln, el in zip(lat, lon, elev): 
    fgv.add_child(folium.Marker(location = [lt, ln], popup = str(el) + " m", icon = folium.Icon(color = color_producer(el))))
    # fg.add_child(folium.CircleMarker(location = [lt, ln], radius = 6, popup = str(el) + " m", fill_color = color_producer(el), color = "black", fill_opacity = 0.5))

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"}))

map.add_child(fgv)
map.add_child(fgp)
map.add_child(folium.LayerControl())
map.save("map1.html")
Exemple #14
0
#coding:utf-8
import folium
import pandas as pd

flags = pd.DataFrame({
    'number': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
    'latitude': [
        35.028309, 46.469391, 39.758949, 41.015137, 24.466667, 3.140853,
        9.005401, -3.989038, 52.377956, 41.085651, 57.790001, 31.205753
    ],
    'longtude': [
        135.753082, 30.740883, -84.191605, 28.979530, 54.366669, 101.693207,
        38.763611, -79.203560, 4.897070, -73.858467, -152.407227, 29.924526
    ]
})

flag_map = folium.Map(location=[35.028309, 135.753082], zoom_start=9)

for i, r in flags.iterrows():
    folium.Marker(location=[r['latitude'], r['longtude']],
                  popup=r['number']).add_to(flag_map)

flag_map
            [lat, lng],
            radius=5, # define how big you want the circle markers to be
            color='yellow',
            fill=True,
            fill_color='blue',
            fill_opacity=0.6
        )
    )

# add pop-up text to each marker on the map
latitudes = list(df_incidents.Y)
longitudes = list(df_incidents.X)
labels = list(df_incidents.Category)

for lat, lng, label in zip(latitudes, longitudes, labels):
    folium.Marker([lat, lng], popup=label).add_to(sanfran_map)    
    
# add incidents to map
sanfran_map.add_child(incidents)

# If you find the map to be so congested will all these markers, there are two remedies to this problem. 
# The simpler solution is to remove these location markers and just add the text to the circle markers themselves as follows:

# create map and display it
sanfran_map = folium.Map(location=[latitude, longitude], zoom_start=12)

# loop through the 100 crimes and add each to the map
for lat, lng, label in zip(df_incidents.Y, df_incidents.X, df_incidents.Category):
    folium.features.CircleMarker(
        [lat, lng],
        radius=5, # define how big you want the circle markers to be
Exemple #16
0
minimap = plugins.MiniMap(toggle_display=True, tile_layer='Stamen Terrain')
kanton_map.add_child(minimap)

#Add FullScreen
plugins.Fullscreen(position='topright',
                   title='Expand me',
                   title_cancel='Exit me',
                   force_separate_button=True).add_to(kanton_map)

#creating a Marker for each point in the above table. Each point will get a popup with their zip
for row in cord.itertuples():
    #html1 = fancy_html(row)
    #iframe = branca.element.IFrame(html=html1,width=400,height=300)
    #popup = folium.Popup(iframe,parse_html=True)
    kanton_map.add_child(
        folium.Marker(location=[row.lat, row.lon], popup=[row.location_area]))
'''
#Applying HTML Visualization to all Markers
for i in range(0,len(cord)):
    html = fancy_html(i)
 
    iframe = branca.element.IFrame(html=html,width=400,height=300)
    popup = folium.Popup(iframe,parse_html=True)
    
    folium.Marker([cord['lat'].iloc[i],cord['lon'].iloc[i]],
                  popup=popup,icon=folium.Icon(icon='info-sign')).add_to(kanton_map)


#Adding Gradient in Heat Map
from folium.plugins import HeatMap
Exemple #17
0
'''
html1 = '''
<br>
City: 
'''
html2 = '''
<br>
Country: 
'''
html3 = '''
<br>
contact:
'''
country = 'city, country =   '
contact = 'contact us =   '
folium.CircleMarker(location=[42.466470, -70.942110],
                    radius=50,
                    popup='OSGeo headquarters',
                    color='#428bca',
                    fill=True,
                    fill_color='#428bca').add_to(m)
for index, row in main.iterrows():
    text = html + row['laboratory'] + html1 + row['city'] + html2 + row[
        'country'] + html3 + row['contact']
    folium.Marker(
        [row['lat'], row['long']],
        popup=folium.Popup(text, max_width=300, min_width=300),
        tooltip=tooltip,
        icon=folium.features.CustomIcon('icon.png', icon_size=(50, 50)),
    ).add_to(m)
m.save('map.html')
Exemple #18
0
ex_wind_power = np.array(posi2["ex_wind_power"][0:num2])  # 获取数据采集时间
ex_conditions = np.array(posi2["ex_conditions"][0:num2])  # 获取数据采集时间
ex_rain_amount = np.array(posi2["ex_rain_amount"][0:num2])  # 获取数据采集时间

route = folium.PolyLine(  #polyline方法为将坐标用线段形式连接起来
    data1,  #将坐标点连接起来
    weight=3,  #线的大小为3
    color='blue',  #线的颜色为橙色
    opacity=0.8  #线的透明度
).add_to(m)  #将这条线添加到刚才的区域m内

for i in range(num1):
    for k in range(num2):
        if location_time[i] == bad_driving_time[k]:
            str_info = '时间:' + bad_driving_time[
                k] + ';    类型:' + bad_driving_name[
                    k] + ';    详细信息:' + bad_driving_info[
                        k] + ';    风力级别:' + ex_wind_power[
                            k] + ';    天气状况:' + ex_conditions[
                                k] + ';    降水量:' + str(ex_rain_amount[k])

            folium.Marker(location=[lat[i], lng[i]],
                          popup=folium.Popup(str_info,
                                             max_width=2650)).add_to(m)

html_path = os.path.join(
    'r', 'E:\\data\\python_file\\bad_driving_exchange_html_file',
    'AA00002_bd_ex.html')
m.save(html_path)  #将结果以HTML形式保存
webbrowser.open(html_path, new=1)
print('恭喜您,转换成功!', '\n')
Exemple #19
0
ax.add_feature(cf.OCEAN)
ax.add_feature(cf.BORDERS)
ax.add_feature(cf.LAND)
ax.set_title("Worldwide Bushfires")
plt.show()

# FOLIUM PART --------------------

# print(content)
m = folium.Map()
tooltip = 'Click me!'
index = 0
print("Length x : ", len(x))
print("Length y : ", len(y))
print(x[392308])
while (index < len(x)):
    # print(x[index], y[index])
    folium.Marker([x[index], y[index]],
                  popup='<i>Mt. Hood Meadows</i>',
                  icon=folium.Icon(color='red', icon='info-sign'),
                  tooltip=tooltip).add_to(m)
    print("Loading ", index)
    index += 1000
''' 
folium.Marker([45.3288, -121.6625],
              popup='<i>Mt. Hood Meadows</i>', tooltip=tooltip).add_to(m) '''
m.save('index.html')
# WEB BROWSER PART ------
url = 'index.html'
webbrowser.open(url, new=2)  # open in new tab
Exemple #20
0
    
    gdf_subset = gdf[(gdf["latitude"] > y_bounds[0]) &
                     (gdf["latitude"] < y_bounds[1]) &
                     (gdf["longitude"] > x_bounds[0]) &
                     (gdf["longitude"] < x_bounds[1])]
    
    m = folium.Map(tiles='openstreetmap', zoom_start=12, location=[37.8, -122.4])

    coord_list = list(zip(gdf_subset.geometry.x, gdf_subset.geometry.y))
    
    grid_1 = interpolate_2d(coord_list, gdf_subset["isostatic_anom"].values,
                            x_bounds=x_bounds, y_bounds=y_bounds)
    
    g = folium.raster_layers.ImageOverlay(grid_1.T[::-1], opacity=0.5,
                                          bounds=[[y_bounds[0], x_bounds[0]], [y_bounds[1], x_bounds[1]]],
                                          colormap=cm.seismic)
    g.add_to(m)
    
    for (k, row) in gdf_subset.iterrows():
        circ = folium.Circle(location=[row.geometry.y, row.geometry.x], radius=1, fill=True)
        circ.add_to(m)
        
    marker = folium.Marker(location=[37.415229, -122.06265])
    marker.add_to(m)
    
    m.save("maptest.html")



    
Exemple #21
0
    def color_change(el):
        if el < 1000:
            return 'green'
        elif 1000 <= el < 10000:
            return 'orange'
        else:
            return 'red'

    map_marker = folium.Map(location=[0, 0], zoom_start=2)

    marker_cluster = MarkerCluster().add_to(map_marker)

    for lat, lon, elevation, Country in zip(lat, lon, elevation, Country):
        folium.Marker(
            location=[lat, lon],
            popup=[Country, elevation],
            icon=folium.Icon(color=color_change(elevation))).add_to(map_marker)
    folium_static(map_marker)

#Update json file for Advanced WorldMap with our Covid data(TotalCases, TotalDeaths and etc.)
with open('World Map Geo JSON data.json') as f:
    Covid_Json_test = json.load(f)

TC = list(Covid_Countries['TotalCases'])
TD = list(Covid_Countries['TotalDeaths'])
AC = list(Covid_Countries['ActiveCases'])
PP = list(Covid_Countries['Population'])

for i in Covid_Json_test['features']:
    info = i['properties']
    for k, index in enumerate(list(Covid_Countries['Country'])):
cmap = folium.colormap.linear.YlOrRd.scale(geo_merge[ft].min(), geo_merge[ft].max())

folium.GeoJson(geo_merge,
               style_function=lambda feature: {
                'fillColor': cmap(feature['properties'][ft]),
                'threshold_scale': [0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400],
                'fillOpacity' : 0.7,
                'weight' : 1, 'color' : 'black'
               }).add_to(m)

cmap.caption = 'Deaths by district'
cmap.add_to(m)

# Add pop-ups

deaths = pd.read_excel('SLA_RoH_Deng.xlsx')
deaths["DATE"] = deaths["DATE"].astype(str)
deaths["NAME"] = deaths["NAME"].astype(str)
deaths["PLACE"] = deaths["PLACE"].astype(str)

my_marker_cluster = folium.MarkerCluster().add_to(m)
for ix, row in deaths.iterrows():
	text = "Name: " + row['NAME'] + "<br>" + "Location: " + str(row['PLACE']) + "<br>" + "Date: " + str(row['DATE'])
	popup = folium.Popup(IFrame(text, width=300, height=100))
	folium.Marker(location = [row['Latitude'],row['Longitude']], popup=popup).add_to(my_marker_cluster)

# Save map

m.save("HeatMap.html")
m
Exemple #23
0
data = pandas.read_csv("Volcanoes.txt")
lat = list(data["LAT"])
lon = list(data["LON"])
name = list(data["NAME"])
elev = list(data["ELEV"])

def iconColor(el):
    if el<1000:
        return 'green'
    elif 1000<=el<3000:
        return 'orange'
    else:
        return 'red'

for lt,ln,nm,el in zip(lat,lon,name,elev):
    fgv.add_child(folium.Marker(location=[lt,ln],popup=str(nm)+" "+str(el),icon=folium.Icon(color=iconColor(el))))

fgp = folium.FeatureGroup(name="Population")
geoData = open('world.json','r',encoding='utf-8-sig').read()
fgp.add_child(folium.GeoJson(data= (geoData),
                            style_function = lambda x:{'fillColor':'green' 
                                                       if x['properties']['POP2005']<10000000 else 'yellow' 
                                                       if 10000000<=x['properties']['POP2005']<20000000 else 'red'}))
map.add_child(fgv)

map.add_child(fgp)

map.add_child(folium.LayerControl())

map.save("Map1.html")
Exemple #24
0
for i in range(len(purple)):
    if purple[i] == 'true':
        line_color.append('purple')
purp2 = [str(x[13]) for x in data]
for i in range(len(purp2)):
    if purp2[i] == 'true':
        line_color.append('purple')
yellow = [str(x[14]) for x in data]
for i in range(len(yellow)):
    if yellow[i] == 'true':
        line_color.append('#FFFF00')
pink = [str(x[15]) for x in data]
for i in range(len(pink)):
    if pink[i] == 'true':
        line_color.append('pink')
orange = [str(x[-16]) for x in data]
for i in range(len(orange)):
    if orange[i] == 'true':
        line_color.append('orange')

print(line_color)

train_map = folium.Map(location=[41.880443, -87.644107], zoom_start=10.4)

for i in range(len(data)):
    folium.Marker(location=location[i],
                  popup=names[i],
                  icon=folium.plugins.BeautifyIcon(
                      border_color=line_color[i]).add_to(train_map))
train_map.save('train_map.html')
Exemple #25
0
def generate_map(data, feature=False, year=2017):
    """ Utiliza el framework Folium para generar el html con la información obtenida 
        de la base de datos. """
    sfMap = folium.Map(location=start_coords, zoom_start=12)
    start = timer()
    total_start = start

    if (feature is None):
        print("    generateMap: without feature")
        marker = folium.plugins.MarkerCluster(name="Density").add_to(sfMap)
        for name, row in data.iterrows():
            folium.Marker([row["Y"], row["X"]],
                          popup=folium.Popup(
                              row["description"])).add_to(marker)
    elif (feature is True):
        callback = (
            'function (row) {'
            'var marker = L.circle(new L.LatLng(row[1], row[0]), {color: "red",  radius: 20000});'
            'marker.bindPopup("example");'
            'return marker};')
        sfMap.add_child(
            FastMarkerCluster(data[['Y', 'X']].values.tolist(),
                              callback=callback))

    else:
        print("    generateMap: with feature", data[['Y', 'X', 'description']])
        MarkerClusterScript(data[['Y', 'X',
                                  'description']].to_json(orient="records"),
                            callback=create_marker).add_to(sfMap)

    print("    generateMap:markers elapsed", timer() - start)
    start = timer()
    district_geo = r'static/datasets/sfpddistricts.geojson'

    incidentsCountPerDistrict = get_per_district(year)
    #if (year == 2017):
    #    incidentsCountPerDistrict = incidentsPerDistrict2017();
    #elif (year == 2016):
    #    incidentsCountPerDistrict = incidentsPerDistrict2016();
    #elif (year == 2015):
    #    incidentsCountPerDistrict = incidentsPerDistrict2015();
    #else:
    #    incidentsCountPerDistrict = []

    # Choropleth. Proporciona las secciones coloreadas para
    # cada distrito
    sfMap.choropleth(geo_data=district_geo,
                     name="Incidents per district",
                     data=incidentsCountPerDistrict,
                     columns=['district', 'count'],
                     key_on='feature.properties.DISTRICT',
                     fill_color='YlOrRd',
                     fill_opacity=0.7,
                     line_opacity=0.2,
                     legend_name='Number of incidents per district')

    folium.LayerControl().add_to(sfMap)

    print("    generateMap:layers elapsed", timer() - start)
    print("generateMap elapsed", timer() - total_start)
    return sfMap
Exemple #26
0
city_list = list(city)
state = df["state"]
states = list(state)
state_list = list(state)

address = [
    city_list[i] + " " + state_list[i] for i in range(0, len(city_list))
]

mapit = folium.Map(location=[20.5937, 78.9629], zoom_start=6)

for i in address:
    loc = geolocator.geocode(i)
    lat = loc.latitude
    long = loc.longitude
    folium.Marker(location=[lat, long], fill_color='#43d9de',
                  radius=8).add_to(mapit)
mapit.save('indiaa.html')

farm_info = {}

for item in states:
    if item in farm_info:
        farm_info[item] += 1
    else:
        farm_info[item] = 1

print(farm_info)

states = list(farm_info.keys())
farm_number = list(farm_info.values())
exp = []
Exemple #27
0
data_frame = pandas.read_csv("Volcanoes_USA.csv")
map = folium.Map(location=[48.7767982, -121.810997])

fg = folium.FeatureGroup(name='My map')
lat = list(data_frame['LAT'])
lon = list(data_frame['LON'])
name = list(data_frame['NAME'])
loc = list(data_frame['LOCATION'])
status = list(data_frame['STATUS'])
elev = list(data_frame['ELEV'])


def mark_color(elevation):
    if elevation > 3000:
        return 'red'
    elif elevation in range(1000, 3000):
        return 'orange'
    else:
        return 'green'


for i, j, nm, lo, st, el in zip(lat, lon, name, loc, status, elev):
    fg.add_child(
        folium.Marker(location=(i, j),
                      popup=folium.Popup(nm + ', ' + lo + ', ' + st + ', ' +
                                         str(el),
                                         parse_html=True),
                      icon=folium.Icon(color=mark_color(el))))
map.add_child(fg)
map.save("Mymap5.html")
# Fron this plot, we can see that a large number of Bar/Cocktail stores have least visitors.  The next cuisines with least footfalls are Izakaya and Dining bar. 

# **Geographical location of low performing stores**



#Marking high and low performance stores by number of visitors
hpstores = dst[dst['visitors'] > 30]
lpstores = dst[dst['visitors'] < 10]




map_osm = folium.Map(location=[40, 140], zoom_start=5)
for lng, lat, desc in zip(hpstores['longitude'], hpstores['latitude'], hpstores['air_genre_name']):
    folium.Marker([lat, lng], popup=desc, icon = folium.Icon(color='blue')).add_to(map_osm)
    

for lng, lat, desc in zip(lpstores['longitude'], lpstores['latitude'], lpstores['air_genre_name']):
    folium.Marker([lat, lng], popup=desc, icon = folium.Icon(color='red')).add_to(map_osm)
map_osm


# We can see the geographical location of high performance stores, where average number of visitors is more than 30 marked in blue, and low performance stores, where average number of visitors is less than 10 marked in red, on the map.
# 





Exemple #29
0

import folium
import pandas

#open the file with pandas.
df = pandas.read_csv("Volcanoes-USA.txt")
map=folium.Map(location=[df['LAT'].mean(),df['LON'].mean()],zoom_start=12,tiles='Stamen Terrain')

#function to select the best color for the marker.
def color(elev):
    minimum = int(df['ELEV'].min())
    step=int((df['ELEV'].max()-df['ELEV'].min())/3)

    if elev in range(minimum,minimum+step):
        col='green'
    elif elev in range(minimum+step, minimum+step*2):
        col='orange'
    else:
        col = 'red'
    return col

#adding markers based on the list 
for lat,lon,name,elev in zip(df['LAT'],df['LON'],df['NAME'],df['ELEV']):
    map.add_child(folium.Marker(location=[lat,lon],popup=name, icon=folium.Icon(color(elev))))
   
#create the html file with the parameters
map.save(outfile='test3.html')
Exemple #30
0
import folium
map3 = folium.Map(location=[15.582987, 73.757706],
                  zoom_start=20,
                  tiles='Stamen Terrain')

folium.Marker(location=[15.582987, 73.757706],
              popup='I am lost',
              icon=folium.Icon(icon='cloud')).add_to(map3)

folium.Marker(location=[15.607220, 73.764229],
              popup='Bu i can see you',
              icon=folium.Icon(color='green')).add_to((map3))

print(map3.save('test3.html'))