예제 #1
0
    else:
        return 'red'


usa_map = folium.Map(location=[40, -100], zoom_start=4, tiles='Stamen Toner')

fgv = folium.FeatureGroup(name='Volcanoes')
fgp = folium.FeatureGroup(name='Population')

for lt, ln, el, name in zip(lat, lon, elv, nm):
    iframe = folium.IFrame(html=html % (name, name, el), width=200, height=80)
    markers = folium.CircleMarker(location=[lt, ln],
                                  popup=folium.Popup(iframe),
                                  radius=5,
                                  stroke=False,
                                  fill_opacity=0.7,
                                  fill_color=elev_color(el))
    fgv.add_child(markers)

fgp.add_child(
    folium.GeoJson(data=(open('world.json', 'r', encoding='utf-8-sig').read()),
                   style_function=lambda x:
                   {'fillColor': pop_color(x['properties']['POP2005'])}))

usa_map.add_child(fgv)
usa_map.add_child(fgp)

usa_map.add_child(folium.LayerControl())

usa_map.save('index.html')
예제 #2
0
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],zoom_start=6,tiles="Mapbox Bright")

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

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

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

map.add_child(fgv)
map.add_child(fgp)
map.add_child(folium.LayerControl())

map.save("Map1.html")
예제 #3
0
                        color=color_selector(row['height']),
                        radius=6,
                        weight=1,
                        fill=True,
                        fill_opacity=0.8))

for i, row in vol_df_a.iterrows():

    iframe = fl.IFrame(html=html % (row['name'], row['name'], row['height']),
                       width=150,
                       height=80)
    fga.add_child(
        fl.Marker(location=[row['lat'], row['lon']],
                  popup=fl.Popup(iframe),
                  icon=fl.Icon(color=color_selector(row['height']))))

fgv.add_child(
    fl.GeoJson(data=open('Data/world.json', 'r', encoding='utf-8-sig').read(),
               style_function=lambda x: {
                   'fillColor':
                   'green'
                   if x['properties']['POP2005'] < 50000000 else 'orange'
                   if x['properties']['POP2005'] < 150000000 else 'red'
               }))

# Adding groups to the map and saving the map

my_map.add_child(fgv)
my_map.add_child(fga)
my_map.save('Results/Map5.html')
예제 #4
0
def visualisation(permutation, iti_matrix, mydf, j_piece):
    j_list = []
    # draw folium graph
    str_fea_list = []
    tooltip = 'Click For More Info'
    des_dict = {
        'WALK': 'Walk to ',
        'SUBWAY': 'Take subway to ',
        'BUS': 'Take bus to '
    }
    m = folium.Map(location=[1.2791, 103.8154], zoom_start=12)
    for i in range(len(permutation) - 1):  # for one itinerary
        sta_plc_idx = permutation[i]
        end_plc_idx = permutation[i + 1]
        itinerary = iti_matrix[sta_plc_idx][end_plc_idx]

        true_sta_pt = np.array((mydf._get_value(sta_plc_idx, 'latitude'),
                                mydf._get_value(sta_plc_idx, 'longitude')))
        true_end_pt = np.array((mydf._get_value(end_plc_idx, 'latitude'),
                                mydf._get_value(end_plc_idx, 'longitude')))

        temp_num_legs = len(itinerary['legs'])  # num of legs
        pt_lat = []
        pt_lon = []
        tpl_list = []
        pt_name = []
        mode_list = []
        dist_list = []
        for k in range(temp_num_legs):  # for each leg
            pt_lon.append(itinerary['legs'][k]['from']['lon'])
            pt_lat.append(itinerary['legs'][k]['from']['lat'])
            tpl_list.append((itinerary['legs'][k]['from']['lon'],
                             itinerary['legs'][k]['from']['lat']))
            pt_name.append(itinerary['legs'][k]['to']['name'])
            mode_list.append(des_dict[itinerary['legs'][k]['mode']])
            dist_list.append(
                str(round(float(itinerary['legs'][k]['distance']) / 1000, 2)) +
                ' km.')
            if k == temp_num_legs - 1:
                pt_lon.append(itinerary['legs'][k]['to']['lon'])
                pt_lat.append(itinerary['legs'][k]['to']['lat'])
                tpl_list.append((itinerary['legs'][k]['to']['lon'],
                                 itinerary['legs'][k]['to']['lat']))
        temp_feature = Feature(geometry=MultiLineString([tpl_list]),
                               properties={'stroke': '#AF4646'})
        str_fea_list.append(temp_feature)
        first_point = np.array((pt_lat[0], pt_lon[0]))

        distance1 = np.linalg.norm(first_point - true_sta_pt)
        distance2 = np.linalg.norm(first_point - true_end_pt)

        start_point = [pt_lat[0], pt_lon[0]]
        end_point = [pt_lat[-1], pt_lon[-1]]
        iterator = range(len(mode_list))
        # only affect formatting the text
        string = ''
        if distance1 > distance2:
            iterator = range(len(mode_list) - 1, -1, -1)
            start_point = [pt_lat[-1], pt_lon[-1]]
            end_point = [pt_lat[0], pt_lon[0]]
        counter = 0
        for j in iterator:
            string += str(counter+1)+'. ' + \
                          mode_list[j]+pt_name[j] + \
                              '. Estimated distance is '+dist_list[j]+'\n'
            counter += 1

        folium.Marker(
            start_point,
            popup='<strong>' + string + '</strong>',
            tooltip=tooltip,
            icon=folium.Icon(icon='trophy' if i != 0 else 'flag')).add_to(m),
        folium.Marker(end_point,
                      icon=folium.Icon(icon='trophy' if i != len(permutation) -
                                       2 else 'star')).add_to(m)

        temp_j_ele = {}
        temp_j_ele['order'] = i + 1
        temp_j_ele['poi_name'] = mydf._get_value(end_plc_idx, 'poi_name')
        temp_j_ele['time_to_spend'] = mydf._get_value(end_plc_idx, 'time')
        temp_j_ele['time_to_travelhere'] = str(
            timedelta(seconds=int(itinerary['duration'])))
        temp_j_ele['description'] = mydf._get_value(end_plc_idx, 'description')
        j_list.append(temp_j_ele)

    j = {'basics': j_piece, 'itinerary': j_list}
    j_file = json.dumps(j)

    feature_collection = FeatureCollection(str_fea_list)
    ms = geojson.dumps(feature_collection)
    folium.GeoJson(ms, name='multistring').add_to(m)

    # Generate map
    render_m = m.get_root().render()

    # insert value into map_database
    map_engine = map_db_init()
    insert_req = "INSERT INTO map_db (id,map_html) VALUES (default," + \
                                      "'"+render_m+"')"
    cursor = map_engine.cursor()
    cursor.execute(insert_req)
    map_engine.commit()

    return j_file
    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...')
예제 #6
0
#This produces the particular area on the map to be shown
map = folium.Map(location=[8.94, 7.22], zoom_start = 6) #tiles="Mapbox Bright")


#Create a featured group for the map so we can call the add_child, it helps when you want to add other features to your map
fgh = folium.FeatureGroup(name="Hotels")

#This produces the markers on the maps
for lt, ln, ad, st in zip(lat, lon, ad, sta):
    fgh.add_child(folium.Marker(location=[lt, ln], popup=ad, tooltip="click to get Address", icon=folium.Icon(color=color_maker(st))))



#featured group for the population color and its attribute
fgp = folium.FeatureGroup(name="Population")

#to add the json file for the polygon attribute:                                     #here we added a lambda function to give our map a population color
fgp.add_child(folium.GeoJson(data=(open('world.json', 'r', encoding='utf-8-sig').read()), style_function =lambda x: {'fillColor':'yellow'
if x['properties']['POP2005'] <10000000 else 'green' }))

map.add_child(fgh)
map.add_child(fgp)

#To turn on and off the feature groups on the map layers
map.add_child(folium.LayerControl())



map.save("Map1.html")
예제 #7
0
    return "green"


map = folium.Map(location=[12.98, 80.24], zoom_start=10, tiles="MapBox Bright")
fgv = folium.FeatureGroup(name='Volcanoes')
#fg.add_child(folium.Marker(location=[12.98,80.24],popup="Hello",icon=folium.Icon(color=color_producer(1000))))
fgv.add_child(
    folium.CircleMarker(location=[12.98, 80.24],
                        radius=6,
                        popup="Hello",
                        fill_color=color_producer(1000),
                        color='grey',
                        fill_opacity=0.7))

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

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

map.add_child(fgv)
map.add_child(fgp)
map.add_child(folium.LayerControl())
map.save("Map1.html")
#print(dir(folium))
예제 #8
0
        folium.CircleMarker(radius=7,
                            location=[lt, ln],
                            popup=n + "\n" + "Elevation: " + str(int(el)) +
                            "m",
                            fill=True,
                            fill_color=elev_color(el),
                            color="gray",
                            fill_opacity=0.7))

# Here, an overlay is being developed to trace each country and then color code it based on population
fg2.add_child(
    folium.GeoJson(data=open("world.json", 'r', encoding="utf-8-sig").read(),
                   style_function=lambda x: {
                       "fillColor":
                       "yellow"
                       if x['properties']['POP2005'] < 10000000 else "green"
                       if x['properties']['POP2005'] < 30000000 else "orange"
                       if x['properties']['POP2005'] < 50000000 else "pink"
                       if x['properties']['POP2005'] < 100000000 else "purple"
                       if x['properties']['POP2005'] < 200000000 else "red"
                   }))

# here the featuregroups are being added to the map along with layer control. fg2 is added before fg1
# so that the circles can still be clicked on without disabling layer from fg2
map.add_child(fg2)
map.add_child(fg1)
map.add_child(folium.LayerControl())

# This saves our map from the program to a local document
map.save("Map1.html")
예제 #9
0
파일: webmap.py 프로젝트: AmanRakesh/WebMap
            radius=6,
            fill_color=color_producer(rt),
            color="grey",
            fill=True,
            fill_opacity=0.7,
        ))

fgP = folium.FeatureGroup(name="Population_Density")

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

fgT = folium.FeatureGroup(name="Temples")

for lt, ln, nm in zip(tlat, tlon, tname):
    iframe = folium.IFrame(html=htmlT % (nm, nm), width=150, height=80)
    fgT.add_child(
        folium.Marker(location=[lt, ln],
                      popup=folium.Popup(iframe),
                      icon=folium.Icon(color="green")))

map.add_child(fgP)
map.add_child(fgW)
예제 #10
0
"""

maps = folium.Map(location=[80, -100], zoom_start=6, tiles="Stamen Terrain")

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

for lt, ln, name, el in zip(lat, lon, v_name, elev):
    v_group.add_child(
        folium.CircleMarker(location=[lt, ln],
                            popup=html % (name, str(el)),
                            fill_color=get_color(el),
                            color="grey"))

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

p_group.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 'red'
                       if x['properties']['POP2005'] > 20000000 else 'orange'
                   }))

maps.add_child(v_group)
maps.add_child(p_group)

maps.add_child(folium.LayerControl())

maps.save("Map1.html")
    def run(self):
        try:
            progressBarStep = 68 * 1000 / (
                self.data['grid']['VERTICAL_CELLS'] *
                self.data['grid']['HORIZONTAL_CELLS'])
            self.update_progresslabel.emit("Построение сети")
            grid = self.data['grid']['geojson']

            map = folium.Map(location=self.data['start'],
                             max_bounds=True,
                             zoom_start=6,
                             max_zoom=6,
                             zoom_control=False,
                             scrollWheelZoom=False)

            map.add_child(
                folium.GeoJson(data=self.data['contour'],
                               style_function=lambda x: {
                                   'color': 'black',
                                   'fillColor': 'transparent'
                               }))

            self.update_progresslabel.emit("Картрирование")

            pokazetel = "prediction"

            # max_temp = -1000.0
            # for k in self.data['map'].keys():
            #     if (self.data['map'][k][pokazetel] > max_temp):
            #         max_temp = self.data['map'][k][pokazetel]

            for i, geo_json in enumerate(grid):
                self.update_progressbar.emit(progressBarStep)
                i_to_row = (self.data['grid']['VERTICAL_CELLS'] -
                            1) - i % self.data['grid']['VERTICAL_CELLS']
                i_to_column = i // self.data['grid']['VERTICAL_CELLS']

                v = self.data['map'][i_to_row, i_to_column][pokazetel]
                if v < 0.5:
                    color = mpl.colors.to_hex('#00ff00')
                elif v >= 0.5 and v < 0.8:
                    color = mpl.colors.to_hex('yellow')
                elif v >= 0.8 and v < 0.92:
                    color = mpl.colors.to_hex('orange')
                else:
                    color = mpl.colors.to_hex('red')
                #color = plt.cm.Reds(self.data['map'][i_to_row, i_to_column][pokazetel] / max_temp)

                border_color = 'black'
                if np.isnan(self.data['map'][i_to_row,
                                             i_to_column][pokazetel]):
                    continue

                gj = folium.GeoJson(
                    geo_json,
                    style_function=lambda feature, color=color: {
                        'fillColor': color,
                        'color': border_color,
                        'weight': 0.5,
                        'fillOpacity': 0.75,
                    })
                popup = folium.Popup(
                    str(i_to_row) + " " + str(i_to_column) + " " +
                    str(self.data['map'][i_to_row, i_to_column][pokazetel]))
                gj.add_child(popup)

                map.add_child(gj)

            map.save('./maps/map.html')
            self.update_mapsignal.emit('./maps/map.html')
        except:
            pass
        self.longtask_finished.emit()
## normalize "congestion index"
# speed_PHF_and_SCARICA["congestion"] = round(speed_PHF_and_SCARICA["congestion_index"]/max(speed_PHF_and_SCARICA["congestion_index"]),2)


# add colors to map
my_map = plot_graph_folium_FK(speed_PHF_and_SCARICA, graph_map=None, popup_attribute=None,
                              zoom=15, fit_bounds=True, edge_width=4, edge_opacity=0.5)
style = {'fillColor': '#00000000', 'color': '#00000000'}
# add 'u' and 'v' as highligths for each edge (in blue)
folium.GeoJson(
    # data to plot
    speed_PHF_and_SCARICA[['u','v', 'scales', 'congestion', 'length', 'geometry']].to_json(),
    show=True,
    style_function=lambda x:style,
    highlight_function=lambda x: {'weight':3,
        'color':'blue',
        'fillOpacity':0.6
    },
    # fields to show
    tooltip=folium.features.GeoJsonTooltip(
        fields=['u', 'v', 'congestion', 'length']
    ),
).add_to(my_map)
folium.TileLayer('cartodbdark_matter').add_to(my_map)
folium.LayerControl().add_to(my_map)
path = 'D:/ENEA_CAS_WORK/Catania_RAFAEL/viasat_data/'
# my_map.save(path + "congestion_Feb_May_Agu_Nov_2019_Catania_all_vehicles.html")
# my_map.save(path + "congestion_August_2019_Catania_all_vehicles.html")
# my_map.save(path + "congestion_February_2019_Catania_all_vehicles.html")
my_map.save(path + "congestion_Feb_May_Agu_Nov_2019_Catania_all_vehicles.html")

예제 #13
0
#                columns=['Id', 'PM2.5'],
#                key_on='feature.properties.Id',
#                data=all_point_data_epa,
#               #threshold_scale=[],
#                fill_color='BuGn',
#                legend_name='pm2.5',
#                line_opacity=0.5,
#                fill_opacity=0.8
#                )
folium.GeoJson(
                taichungmap_1x1,
                name='PM2.5',
                style_function=lambda x: {
                                                    'fillColor': map_color(x['properties'][variable]),
                                                    'color': 'black',
                                                    'weight': 0.5,
                                                    'fillOpacity': 0.7
                                                },
               highlight_function=lambda x: {'weight':3, 'color':'black'},
               tooltip=folium.GeoJsonTooltip(fields=['Id','PM2.5'],aliases=['Id','PM2.5'],labels=True,sticky=True)

                ).add_to(fmap)
folium.GeoJson(
               taichung_district,
               name='台中各區天氣',
               style_function=lambda x: {"weight":1, 'color':'#5499c7'},
               highlight_function=lambda x: {'weight':3, 'color':'#2471A3'},
               tooltip=folium.GeoJsonTooltip(fields=['區名','天氣','溫度','降雨預報'],aliases=['區名','天氣','溫度','降雨機率'],labels=True,sticky=False),
               show=False
              ).add_to(fmap)
#fmap.choropleth(
from folium import plugins

#CSV -  store location
df = pd.read_csv('starbucksInLACounty.csv')

#shape Los Angeles
with open('laMap.geojson') as f:
    laArea = json.load(f)

#start map as folium object
mapa = folium.Map(location=[34.0522, -118.2437],
                  tiles='Stamen Toner',
                  zoom_start=9)

#add shape
folium.GeoJson(laArea).add_to(mapa)

#extract latitude longitude
#plot dots as circles
for i, row in df.iterrows():
    folium.CircleMarker((row.latitude, row.longitude),
                        radius=3,
                        weight=2,
                        color='red',
                        fill_color='red',
                        fill_opacity=.5).add_to(mapa)

#save map as html
mapa.save('laPointMap.html')

#########################
예제 #15
0
def main():
	locations_dir = './locations/'
	visited_cities_list = 'visited-cities.csv'
	nvisited_cities_list = 'want-to-visit.csv'
	visited_geos_dir = '{}{}'.format(locations_dir, 'visited/')
	nvisited_geos_dir = '{}{}'.format(locations_dir, 'want-to-visit/')

	# Get Lat and Long of cities
	geolocator = Nominatim(timeout=1000000)

	# For cities that I have vistied
	visited_lats_longs = []
	visited_cities = []

	# For cities I want to visit
	nvisited_lats_longs = []
	nvisited_cities = []

	visited_df = pandas.read_csv(
		'{}{}'.format(
			locations_dir,
			visited_cities_list),
		sep=',')
	visited_rows = visited_df.shape[0]

	nvisited_df = pandas.read_csv(
		'{}{}'.format(
			locations_dir,
			nvisited_cities_list),
		sep=',')
	nvisited_rows = nvisited_df.shape[0]

	# Add the cities I've visited to a list
	print("Visited Cities:")
	for x in range(visited_rows):
		d = visited_df.iloc[x]['Visited Cities']
		print(d)
		visited_cities.append(d)

	# Add the cities that I want to visit to a list
	print("\nCities I Want to Visit")
	for x in range(nvisited_rows):
		d = nvisited_df.iloc[x]['Want to Visit']
		print(d)
		nvisited_cities.append(d)

	# Get the latitude and logitude of cities I have visited
	print("\nCoordinates of cities I have visited")
	for city in visited_cities:
		location = geolocator.geocode(city)
		print(location)
		visited_lats_longs.append([location.latitude, location.longitude])

	# Get the latitude and logitudes of cities that I want to visit
	print("\nCoordinates of cities I want to visit")
	for city in nvisited_cities:
		location = geolocator.geocode(city)
		print(location)
		nvisited_lats_longs.append([location.latitude, location.longitude])


	# Sanity check
	for result in visited_lats_longs:
		print(result[0], result[1])

	for result in nvisited_lats_longs:
		print(result[0], result[1])

	# Note: Need to confirm differente between add_child and add_to

	f = folium.Figure(width=1000, height=500)  # Instantiate a figure
	travel_map = folium.Map(location=[0, 0], zoom_start=2, min_zoom=2).add_to(
		f)  # Instantiate a world map and add it to the figure
	# Add Latitude Longitude Popup to the map
	travel_map.add_child(folium.features.LatLngPopup())
	fs = Externals.Fullscreen()
	szt = Externals.ScrollZoomToggler()

	fs.add_to(travel_map)  # Add a Fullscreen button to the map (plugin)
	# Add the scroll zoom toggler button to the map (plugin)
	szt.add_to(travel_map)

	# Colorscale: Steps of 10 between 0 and 200
	colorscale = cm.linear.PuRd.scale(0, 200)
	colorscale.caption = 'Total number of days spent in each location (Coming Soon)'
	travel_map.add_child(colorscale)

	"""
	Add the .geo.json data for countries to the map first
	"""
	# Get *.geo.json for visited countries
	for root, dirs, files in os.walk(visited_geos_dir):
		visited_jsons = files
		print(visited_jsons)

	# Get *.geo.json for countries not visited
	for root, dirs, files in os.walk(nvisited_geos_dir):
		nvisited_jsons = files
		print(nvisited_jsons)

	# Create feature groups for the countries
	visited_map_countries = folium.FeatureGroup(name='Countries I\'ve Visited')
	nvisited_map_countries = folium.FeatureGroup(name='Countries I want to visit')

	y = 0  # Indexing for countries that I haven't visited
	for x in range(0, len(visited_jsons) + len(nvisited_jsons)):
		if x < len(visited_jsons):  # For visited countries
			map_loc = folium.GeoJson(
				open(
					'{}{}'.format(
						visited_geos_dir,
						visited_jsons[x]),
					encoding="utf-8-sig").read(),
				style_function=lambda x: {
					'fillColor': 'green',
					'dashArray': '5, 5'},
				highlight_function=lambda x: {
					'weight': 2,
					'fillColor': 'blue'})  # Load the .geo.json data and customize
			# Add the GeoJSON to the map_countries feature group
			visited_map_countries.add_child(map_loc)

		else:  # For countries not yet visited
			map_loc = folium.GeoJson(
				open(
					'{}{}'.format(
						nvisited_geos_dir,
						nvisited_jsons[y]),
					encoding="utf-8-sig").read(),
				style_function=lambda x: {
					'fillColor': 'red',
					'dashArray': '5, 5'},
				highlight_function=lambda x: {
					'weight': 2,
					'fillColor': 'blue'})  # Load the .geo.json data and customize
			# Add the GeoJSON to the map_countries feature group
			nvisited_map_countries.add_child(map_loc)
			y += 1

	visited_map_countries.add_to(travel_map)  # Add the feature group to the map
	nvisited_map_countries.add_to(travel_map)  # Add the feature group to the map

	"""
	Next, add the processed geopy data for cities
	"""
	visited_map_cities = folium.FeatureGroup(name='Cities I\'ve Visited')
	nvisited_map_cities = folium.FeatureGroup(name='Cities I want to visit')

	y = 0  # Indexing for cities that I haven't visited
	for x in range(0, len(visited_lats_longs) + len(nvisited_lats_longs)):
		if x < len(visited_lats_longs):  # For visited cities
			mkr = folium.Marker(
				[
					visited_lats_longs[x][0],
					visited_lats_longs[x][1]],
				popup=visited_df.iloc[x]['Visited Cities'],
				icon=folium.Icon(
					color='green',
					prefix='fa',
					icon='plane'))  # Add a marker to show the name of the city located at the marker on click
			# Add the marker to the feature group
			visited_map_cities.add_child(mkr)
		else:  # For cities not yet visited
			mkr = folium.Marker(
				[
					nvisited_lats_longs[y][0],
					nvisited_lats_longs[y][1]],
				popup=nvisited_df.iloc[y]['Want to Visit'],
				icon=folium.Icon(
					color='red',
					prefix='fa',
					icon='plane'))  # Add a marker to show the name of the city located at the marker on click
			# Add the marker to the feature group
			nvisited_map_cities.add_child(mkr)
			y += 1

	visited_map_cities.add_to(travel_map)  # Add the feature group to the map
	nvisited_map_cities.add_to(travel_map)  # Add the feature group to the map

	folium.LayerControl().add_to(travel_map)  # Add Layer Controller to the map

	# Add a legend
	legend_html = '''
		<div style="position: fixed;
			bottom: 50px; left: 50px; width: 100px; height: 90px;
			border:2px solid grey; z-index:9999; font-size:14px;
			">&nbsp; Legend <br>
			  &nbsp; Visited &nbsp; <i class="fa fa-map-marker fa-2x" style="color:green"></i><br>
			  &nbsp; Will Visit &nbsp; <i class="fa fa-map-marker fa-2x" style="color:red"></i>
		</div>
	'''
	travel_map.get_root().html.add_child(folium.Element(legend_html))

	travel_map.save('index.html')
예제 #16
0
    geoZone["geometry"]["coordinates"] = []
    geoZone["geometry"]["coordinates"].append(c)
    outGeoJson["features"].append(geoZone)
'''
Draw on the map a gray square
'''
lat = zones.loc[136]["Lat"]
lon = zones.loc[136]["Lon"]
map_5 = folium.Map(
    location=[lat, lon],
    zoom_start=12.25,
)
folium.GeoJson(outGeoJson,
               style_function=lambda feature: {
                   'fillColor': 'gray',
                   'color': 'black',
                   'fillOpacity': 0.2,
                   'weight': 1,
               }).add_to(map_5)
'''
Covertion of CS df into GeoJson
'''
outGeoJson = {"type": "FeatureCollection", "features": []}
f = open("./data/" + city + "squares_CS.json", 'w')
for i in range(len(CS_in_sol)):
    a, b, c = createGeoJson(CS_in_sol.iloc[i], metric)
    geoZone = {}
    geoZone["type"] = "Feature"
    geoZone["zone"] = float(a)
    geoZone["geometry"] = {}
    geoZone["geometry"]["type"] = "Polygon"
MERGED_clean_EDGES.drop_duplicates(['u', 'v'], inplace=True)
'''
AAA = MERGED_clean_EDGES[MERGED_clean_EDGES['u'] == 33589436]
AAA.u
AAA.v
AAA.records
AAA.color
'''

#############################################################################################
# create basemap
ave_LAT = 37.53988692816245
ave_LON = 15.044971594798902
my_map = folium.Map([ave_LAT, ave_LON], zoom_start=11, tiles='cartodbpositron')
#############################################################################################
'''
clean_edges_matched_route.geometry.to_file(filename='clean_matched_route.geojson', driver='GeoJSON')
folium.GeoJson('clean_matched_route.geojson').add_to(my_map)
my_map.save("clean_matched_route.html")
'''

# add colors to map
my_map = plot_graph_folium_FK(MERGED_clean_EDGES,
                              graph_map=None,
                              popup_attribute=None,
                              zoom=1,
                              fit_bounds=True,
                              edge_width=4,
                              edge_opacity=1)  # tiles='cartodbpositron'
my_map.save("clean_matched_route.html")
예제 #18
0
def create_heatmap(mapname, index_input_file, period_for_heatmap_parameter):

    # Info: print the version of folium
    print("Folium Version: " + folium.__version__)

    # Get the lower-left and upper-right bounds from the Municipi shapes to center the map
    administrative_subdivision_shape_bounds = folium.GeoJson(
        config.administrative_subdivision_geojson_file).get_bounds()
    city_coords = [
        administrative_subdivision_shape_bounds[0][0] +
        (administrative_subdivision_shape_bounds[1][0] -
         administrative_subdivision_shape_bounds[0][0]) / 2,
        administrative_subdivision_shape_bounds[0][1] +
        (administrative_subdivision_shape_bounds[1][1] -
         administrative_subdivision_shape_bounds[0][1]) / 2
    ]
    print('Boundaries of the map are {}'.format(
        administrative_subdivision_shape_bounds))
    print('Centre of the map of {} is {}'.format(config.city_name,
                                                 city_coords))

    # Prepare the choropleth for the administrative subdivisions (e.g. Roma Municipi)
    choropleth = folium.Choropleth(
        geo_data=config.administrative_subdivision_geojson_file,
        name=config.city_name + ' Administrative Subdivisions',
        columns=['nome'],
        key_on='feature.properties.nome',
        fill_color='YlGn',
        fill_opacity=0,
        line_opacity=0.5,
        legend_name='{} Administrative Subdivisions'.format(config.city_name))

    # Prepares the grid for city blocks
    map_grid = folium.Choropleth(
        geo_data='./input_data/city_grid.geojson',
        name=config.city_name + ' City Grid',
        columns=['administrative_subdivision', 'block_ID'],
        fill_color='RdPu',
        fill_opacity=0,
        line_opacity=0.1,
        line_color='blue',
        show=False)

    # Adds a tooltip
    #choropleth.geojson.add_child( folium.features.GeoJsonTooltip(['administrative_subdivision']))
    map_grid.geojson.add_child(
        folium.features.GeoJsonTooltip(
            ['administrative_subdivision', 'block_ID'],
            aliases=['Administrative Subdivision', 'Block Identifier']))

    # Creates the city map
    city_map = folium.Map(location=city_coords,
                          zoom_start=12,
                          min_zoom=10,
                          max_zoom=15,
                          control_scale=True)

    # Adds different map layers
    folium.TileLayer('cartodbpositron').add_to(city_map)
    folium.TileLayer('cartodbdark_matter').add_to(city_map)

    # Adds the administrative subdivisions and city grid
    choropleth.add_to(city_map)
    map_grid.add_to(city_map)

    # Creates the heatmap correspinding to the index file provided as argument and adds it to the map
    heatmap_with_time = createHeatMapWithTimeFromIndexFile(
        index_input_file, period_for_heatmap_parameter,
        mapname).add_to(city_map)
    folium.LayerControl(collapsed=False).add_to(city_map)

    # Save the map and display it using a web browser
    mapFileName = os.path.join(
        'map',
        get_file_name('html', 'Heatmap', mapname.replace(" ", "_"),
                      period_for_heatmap_parameter))
    city_map.save(mapFileName)
    print("Saving the generated map in: " + mapFileName)
    webbrowser.open(mapFileName, new=2)
예제 #19
0
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=3, tiles='Stamen Terrain')

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

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

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'] < 30000000 else 'blue'
    if 30000000 <= x['properties']['POP2005'] < 100000000 else 'red'}))

map.add_child(fgv)
map.add_child(fgp)
map.add_child(folium.LayerControl())

map.save("Map1.html")
예제 #20
0
crime_chicago_count_gpd['style'] = crime_chicago_count_gpd[
    'relative_count'].map(lambda x: {
        'fillColor': linear(x),
        'weight': 0
    })

# In[161]:

crime_chicago_count_gpd.crs = {'init': 'epsg:4326', 'no_defs': True}

# In[162]:

m = folium.Map([41.80, -87.75], zoom_start=11, tiles='cartodbpositron')

folium.GeoJson(crime_chicago_count_gpd).add_to(m)

# In[163]:

m.add_children(
    folium.Marker([41.868648, -87.640007],
                  popup="The Maxwell",
                  icon=folium.Icon(color='gray')))
m.add_children(
    folium.Marker([41.897754, -87.623944],
                  popup="Water Tower Place",
                  icon=folium.Icon(color='gray')))
m.add_children(
    folium.Marker([41.899274, -87.624524],
                  popup="900 North Michigan Shops",
                  icon=folium.Icon(color='gray')))
예제 #21
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
예제 #22
0
def folium_map(geojson_to_overlay,
               layer_name,
               location,
               style_function=None,
               tiles='Stamen Terrain',
               zoom_start=16,
               show_layer_control=True,
               width='100%',
               height='75%',
               attr=None,
               map_zoom=18,
               max_zoom=20,
               tms=False,
               zoom_beyond_max=None,
               base_tiles='OpenStreetMap',
               opacity=1):
    """Folium map with Geojson layer and TMS tiles layer.
    This function requires geojson_to_overlay (geojson), layer_name (String), and location (map center tuple).
    You can also set tiles to the TMS URL and control map zoom."""

    m = folium.Map(location=location,
                   zoom_start=zoom_start,
                   width=width,
                   height=height,
                   max_zoom=map_zoom,
                   tiles=base_tiles)
    tiles = folium.TileLayer(tiles=tiles,
                             attr=attr,
                             name=attr,
                             max_zoom=max_zoom)
    if tms is True:
        options = json.loads(tiles.options)
        options.update({'tms': True})
        tiles.options = json.dumps(options, sort_keys=True, indent=2)
        tiles._template = jinja2.Template(u"""
        {% macro script(this, kwargs) %}
            var {{this.get_name()}} = L.tileLayer(
                '{{this.tiles}}',
                {{ this.options }}
                ).addTo({{this._parent.get_name()}});
        {% endmacro %}
        """)
    if zoom_beyond_max is not None:
        options = json.loads(tiles.options)
        options.update({'maxNativeZoom': zoom_beyond_max, 'maxZoom': max_zoom})
        tiles.options = json.dumps(options, sort_keys=True, indent=2)
        tiles._template = jinja2.Template(u"""
        {% macro script(this, kwargs) %}
            var {{this.get_name()}} = L.tileLayer(
                '{{this.tiles}}',
                {{ this.options }}
                ).addTo({{this._parent.get_name()}});
        {% endmacro %}
        """)
    if opacity < 1:
        options = json.loads(tiles.options)
        options.update({'opacity': opacity})
        tiles.options = json.dumps(options, sort_keys=True, indent=2)
        tiles._template = jinja2.Template(u"""
        {% macro script(this, kwargs) %}
            var {{this.get_name()}} = L.tileLayer(
                '{{this.tiles}}',
                {{ this.options }}
                ).addTo({{this._parent.get_name()}});
        {% endmacro %}
        """)

    tiles.add_to(m)
    if style_function is not None:
        gj = folium.GeoJson(geojson_to_overlay,
                            overlay=True,
                            name=layer_name,
                            style_function=style_function)
    else:
        gj = folium.GeoJson(geojson_to_overlay, overlay=True, name=layer_name)
    gj.add_to(m)

    if show_layer_control is True:
        folium.LayerControl().add_to(m)

    return m
예제 #23
0
VPUs.to_crs({
    'init': 'epsg:4326'
}).to_file(r"%s\boundary.json" % out, driver="GeoJSON")

t = VPUs.centroid
type(t)
t = VPUs.bounds
lat_Center = (t.miny.min() + t.maxy.max()) / 2
lon_Center = (t.maxx.max() + t.minx.min()) / 2

f_map = folium.Map(location=[lat_Center, lon_Center],
                   zoom_start=6,
                   tiles="Stamen Terrain")

f_map.add_child(
    folium.GeoJson(data=open(r"%s\vpu_lines_needed.json" % out),
                   name='VPU Boundaries'))

f_map.save(outfile=r'%s\interVPU.html' % out)

## code to get problem sites out of NRSA1314
keep = [
    'FLS9-0919', 'FLS9-0921', 'IAR9-0914', 'MNSS-1172', 'OKRF-0005',
    'OKRF-0101', 'ORRF-0107', 'PASS-1166', 'TXRF-0002', 'WARF-0110'
]
sites = gpd.read_file(
    r'L:\Priv\CORFiles\Geospatial_Library\Data\Project\StreamCat\NRSA13_14_SiteData.shp'
)
sites.columns.tolist()
new = sites.ix[sites.SITE_.isin(keep)]
new.crs
new.to_file(r'D:\Projects\temp\NRSA1314_probsites\sites_10.shp')
예제 #24
0
#x, y = (-61.413723,15.402079) # should return 5 & Pol_16 # this is outside the AOI clip

#longitude=x; latitude=y
#-------------------

# Show Map

# Fill polygons in Folium *** https://stackoverflow.com/questions/35516318/plot-colored-polygons-with-geodataframe-in-folium ***
colors = ['#2b83ba', '#abdda4', '#ffffbf', '#fdae61', '#d7191c'] # these have been assigned to each FloodRisk category in the GeoJSON file on QGIS!!!

m = folium.Map(location=[15.4275, -61.3408], zoom_start=10) # center of island overview
#m = folium.Map(location=[15.420138, -61.381893], zoom_start=16)

# Show Landslide GeoJSON to the map
folium.GeoJson(
    landslide_json,
    name='Landslide'
).add_to(m)

# Setup colormap MUST USE SAME COLORS AS QGIS GEOJSON FILE!!!!
levels = len(colors)
cmap = branca.colormap.LinearColormap(colors, vmin=1, vmax=5).to_step(levels-1)
cmap.add_to(m)

folium.GeoJson(
    flood_gj,
    name='Flood Risk',
    style_function=lambda feature: {
        'fillColor': feature['properties']['Color'],
        'color' : feature['properties']['Color'],
        'weight' : 1,
        'fillOpacity' : 0.3,
예제 #25
0
import folium
from folium.element import IFrame
from geopy.geocoders import Nominatim

m = folium.Map([24, 84],
               zoom_start=5)

folium.TileLayer('Mapbox Bright').add_to(m)

ft = "Polity_score"
cmap = folium.colormap.linear.YlGn.to_step(9).scale(polity_merge[ft].min(), polity_merge[ft].max())

folium.GeoJson(polity_merge,
               style_function=lambda feature: {
                'fillColor': cmap(feature['properties'][ft]),
                'fillOpacity' : 0.95,
                'weight' : 1, 'color' : 'black'
               }).add_to(m)

cmap.caption = 'Polity Score Scale'
cmap.add_to(m)

folium.GeoJson(result_country,
               style_function=lambda feature: {'weight': 2, 'color':'black'}).add_to(m)

terminated_groups = terminated
terminated_groups["fullname"] = terminated_groups["fullname"].astype(str)

not_terminated_groups = not_terminated
not_terminated_groups["fullname"] = not_terminated_groups["fullname"].astype(str)
예제 #26
0
    def grid_plot(self, boundaries, colors, legend=True):
        """Function to plot the probability grid and determine the color of each square based on probability

        Args:
         -boundaries(list): The boundaries determining the color of each square. The first and last element
                             be 0 and 1 respectively and all elements must be strictly increasing


         -colors(list): The length must the be equal to the length of the boundaries list - 1

         -legend(boolean): Whether to include a legend the default is true

         The boundary from the ith to the i+1 index in the boundaries list maps to the ith color in the
         colors list. Hence the requirements on the lengths

        Returns:
            The map with the probability grid superimposed
        """

        # Checking if the arguments are of a valid length
        self.bound_col_checks(boundaries=boundaries, colors=colors)

        north = self.north
        south = self.south
        east = self.east
        west = self.west

        gmm = self.gmm

        grid_df = self.grid_df()

        grid_perc_array = np.array(grid_df['probability'])

        # Code to find the color for each square based on probability
        color_array = []

        for grid_perc in grid_perc_array:

            for bound_idx in range(len(boundaries) - 1, -1, -1):

                boundary = boundaries[bound_idx]

                if grid_perc >= boundary:
                    color_array.append(colors[bound_idx])
                    break

        # Defining a geojson grid and plotting it on a map
        geojson_grid = self.get_geojson_grid(upper_right=(north, east),
                                             lower_left=(south, west),
                                             n=self.squares)

        for idx, box in enumerate(geojson_grid):
            geo_json = json.dumps(box)

            color = color_array[idx]

            popup = folium.Popup(grid_perc_array[idx])

            grid_square = folium.GeoJson(
                geo_json,
                style_function=lambda feature, color=color: {
                    'fillColor': color,
                    'color': "black",
                    'weight': 2,
                    'dashArray': '5, 5',
                    'fillOpacity': 0.55,
                })
            grid_square.add_child(popup)

            mp = self.mp

            mp.add_child(grid_square)

        if legend == True:
            mp = self.legend_maker(mp=mp, boundaries=boundaries, colors=colors)

        return mp
예제 #27
0
    elif elev <= 1000:
        return "red"
listelevation = list(data_volcano["ELEV"])
data_volcano.drop(data_volcano.columns[[i for i in range(8)]], axis = 1, inplace=True)

for index,rows in data_volcano.iterrows():
    fgv.add_child(folium.CircleMarker(location=[rows["LAT"], rows["LON"]], radius=6, popup = str(listelevation[index]), fill_color = get_color(listelevation[index]), color="grey", fill_opacity= 0.7 ))


# In[84]:


fgp = folium.FeatureGroup(name="Population Map")
fgp.add_child(folium.GeoJson(data=open('C:/Users/pavneet9/Downloads/world.json', 'r', encoding='utf-8-sig'),
                            style_function= lambda x:{ fill_color: yellow if x["Properties"]["POP2005"] > 1000000
                                                     else "orange" if 1000000 <= x["Properties"]["POP2005"] <= 2000000
                                                     else "red"}
                           ))
#fg.add_child(folium.GeoJson( data=(open('C:/Users/pavneet9/Downloads/world.json', 'r', encoding='UTF-8-sig').read() )))


# In[83]:


map.add_child(fgv)


map.add_child(folium.LayerControl())
map.save("C:/Users/pavneet9/Downloads/map.html", zoom =6, tiles="Mapbox Bright")

예제 #28
0
    def generateMap2(self,
                     builds=None,
                     rivers=None,
                     roi=None,
                     poly_rivers=None,
                     superpixels=None,
                     bounding=None):

        _map = folium.Map(location=self._location,
                          zoom_start=self._zoom,
                          attr='Ocupación en zonas de ronda hídrica',
                          max_zoom=18,
                          min_zoom=10)
        FloatImage(IMAGE, bottom=81, left=1).add_to(_map)
        FloatImage(IMAGE2, bottom=95, left=12).add_to(_map)
        FloatImage(IMAGE2, bottom=7, left=12).add_to(_map)
        _map.add_tile_layer(self._url,
                            name='Satelital',
                            attr='Ocupación en zonas de ronda hídrica',
                            max_zoom=18,
                            min_zoom=10)
        _map.add_child(folium.LatLngPopup())

        if builds is not None:
            gjson = builds.to_json()
            lay_builds = folium.FeatureGroup(
                name='Construcciones dentro de ronda hidrica')
            lay_builds.add_child(
                folium.GeoJson(data=gjson,
                               style_function=lambda x: {
                                   'color': '#000000',
                                   'weight': 0.15,
                                   'fillColor': '#F08615',
                                   'fillOpacity': 1.0
                               }))
            _map.add_child(lay_builds)

        if superpixels is not None:
            gjson = superpixels.to_json()
            lay_sp = folium.FeatureGroup(
                name='Regiones dentro de ronda hidrica')
            lay_sp.add_child(
                folium.GeoJson(data=gjson,
                               style_function=lambda x: {
                                   'color': '#F08615',
                                   'weight': 2,
                                   'fillColor': '#3DCF58',
                                   'fillOpacity': 0.1
                               }))
            _map.add_child(lay_sp)

        if rivers is not None:
            gjson = rivers.to_json()
            lay_rivers = folium.FeatureGroup(name='Rios')
            lay_rivers.add_child(
                folium.GeoJson(data=gjson,
                               style_function=lambda x: {
                                   'color': '#0083E9',
                                   'opacity': 0.8,
                                   'fillColor': '#0083E9',
                                   'fillOpacity': 1,
                                   'width': 0.1
                               }))
            if poly_rivers is not None:
                gjson = poly_rivers.to_json()
                lay_rivers.add_child(
                    folium.GeoJson(data=gjson,
                                   style_function=lambda x: {
                                       'color': '#0083E9',
                                       'opacity': 0.8,
                                       'fillColor': '#0083E9',
                                       'fillOpacity': 1,
                                       'width': 0.1
                                   }))
            _map.add_child(lay_rivers)

        if roi is not None:
            gjson = roi.to_json()
            lay_susceptibilidad = folium.FeatureGroup(name="Ronda Hidrica")
            lay_susceptibilidad.add_child(
                folium.GeoJson(data=gjson,
                               style_function=lambda x: {
                                   'color': '#B70015',
                                   'opacity': 0.2,
                                   'fillColor': '#B70015',
                                   'fillOpacity': 0.3,
                                   'width': 0.1
                               }))
            _map.add_child(lay_susceptibilidad)

        if bounding is not None:
            lat2, lon1, lat1, lon2 = bounding
            points = [(lat1, lon1), (lat1, lon2), (lat2, lon2), (lat2, lon1),
                      (lat1, lon1)]
            folium.PolyLine(points,
                            weight=1.5,
                            opacity=0.5,
                            dashArray=[20, 20],
                            dashOffset=20).add_to(_map)

        _map.add_child(folium.LayerControl())

        _map.save('temp2.html')

        return _map
예제 #29
0
                           height=200)

    ftgroup_volcano.add_child(
        folium.CircleMarker(location=[lt, ln],
                            radius=12,
                            popup=folium.Popup(iframe),
                            tooltip=na,
                            fillColor=color_producer(elev),
                            color=color_producer(elev),
                            fill=True,
                            fillOpacity=0.7))

#Adds colors according to country population
ftgroup_population.add_child(
    folium.GeoJson(
        data=open('world.json', 'r', encoding="utf-8-sig").read(),
        style_function=lambda x: {
            'fillColor':
            'green' if x['properties']['POP2005'] < 1000000 else 'yellow'
            if 1000000 <= x['properties']['POP2005'] < 20000000 else 'red'
        }))

#Assign feature groups to map
map.add_child(ftgroup_volcano)
map.add_child(ftgroup_population)

#Layer control
map.add_child(folium.LayerControl())

#Create the html file
map.save("Map1.html")
예제 #30
0
파일: job.py 프로젝트: aragatsYara/up42-py
    def map_results(self, show_images=True, name_column: str = "uid") -> None:
        """
        Displays data.json, and if available, one or multiple results geotiffs.

        Args:
            show_images: Shows images if True (default), only features if False.
            name_column: Name of the column that provides the Feature/Layer name.
        # TODO: Make generic with scene_id column integrated.
        """
        if self.results is None:
            raise ValueError(
                "You first need to download the results via job.download_results()!"
            )

        def _style_function(feature):  # pylint: disable=unused-argument
            return {
                "fillColor": "#5288c4",
                "color": "blue",
                "weight": 2.5,
                "dashArray": "5, 5",
            }

        def _highlight_function(feature):  # pylint: disable=unused-argument
            return {
                "fillColor": "#ffaf00",
                "color": "red",
                "weight": 3.5,
                "dashArray": "5, 5",
            }

        # Add feature to map.
        df: GeoDataFrame = self.get_results_json(
            as_dataframe=True)  # type: ignore
        centroid = box(*df.total_bounds).centroid
        m = folium_base_map(
            lat=centroid.y,
            lon=centroid.x,
        )

        for idx, row in 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=_style_function,
                highlight_function=_highlight_function,
            )
            folium.Popup(
                f"{layer_name}: {row.drop('geometry', axis=0).to_json()}"
            ).add_to(f)
            f.add_to(m)
            # Same: folium.GeoJson(df, name=name_column, style_function=style_function,
            # highlight_function=highlight_function).add_to(map)

        # Add image to map.
        if show_images and self.results is not None:
            plot_file_format = [".tif"]
            plottable_images = [
                path for path in self.results
                if Path(path).suffix in plot_file_format
            ]

            if plottable_images:
                dst_crs = "EPSG:4326"
                filepaths: List[Path] = self.results
                try:
                    feature_names = df[name_column].to_list()
                except KeyError:
                    feature_names = ["" for i in range(df.shape[0])]
                for idx, (raster_fp, feature_name) in enumerate(
                        zip(filepaths, feature_names)):
                    # TODO: Not ideal, streaming images are webmercator, folium requires wgs 84.0
                    # TODO: Switch to ipyleaflet!
                    # This requires reprojecting on the user pc, not via the api.
                    # Reproject raster and add to map
                    with rasterio.open(raster_fp) as src:
                        dst_profile = src.meta.copy()

                        if src.crs == dst_crs:
                            dst_array = src.read()[:3, :, :]
                            minx, miny, maxx, maxy = src.bounds
                        else:
                            transform, width, height = calculate_default_transform(
                                src.crs, dst_crs, src.width, src.height,
                                *src.bounds)
                            dst_profile.update({
                                "crs": dst_crs,
                                "transform": transform,
                                "width": width,
                                "height": height,
                            })

                            with MemoryFile() as memfile:
                                with memfile.open(**dst_profile) as mem:
                                    for i in range(1, src.count + 1):
                                        reproject(
                                            source=rasterio.band(src, i),
                                            destination=rasterio.band(mem, i),
                                            src_transform=src.transform,
                                            src_crs=src.crs,
                                            dst_transform=transform,
                                            dst_crs=dst_crs,
                                            resampling=Resampling.nearest,
                                        )

                                    dst_array = mem.read()[:3, :, :]
                                    minx, miny, maxx, maxy = mem.bounds

                    # TODO: Make band configuration available
                    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.
        if df.shape[0] > 4:  # pylint: disable=simplifiable-if-statement  #type: ignore
            collapsed = True
        else:
            collapsed = False
        folium.LayerControl(position="bottomleft",
                            collapsed=collapsed).add_to(m)

        try:
            assert get_ipython() is not None
            display(m)
        except (AssertionError, NameError):
            logger.info(
                "Returning folium map object. To display it directly run in a "
                "Jupyter notebook!")
            return m