def add_point(map, x, y, size, label, marker=settings.MARKER, color=settings.MARKER_COLOR): """ Add one point to the map :param map: a folim map object :param x: longitude WGS84 :param y: latitude WGS84 :param size: marker size :param label: marker label :param marker: a font-awesome marker :return: None """ s = get_class_size(size) folium.map.Marker( location=[y, x], popup=label, icon=DivIcon( #icon_size=(150,36), icon_anchor=(0, 0), html='<i class="fa ' + marker + ' ' + s + '" style="color:' + color + '" aria-hidden="true"></i>', )).add_to(map)
def _marker(self, lat, long, text, xmap, color=None, icon=None, text_mark=False, style=None): """ Adds a marker to the default map """ kwargs = {} if icon is not None: kwargs["icon"] = icon if color is not None: kwargs["color"] = color if style is None: style = "font-size:18pt;font-weight:bold;" + \ "color:black;border-radius:0.5" try: xicon1 = folium.Icon(**kwargs) if text_mark is True: xicon = DivIcon( icon_size=(150, 36), icon_anchor=(0, 0), html='<div style="' + style + '">' + text + '</div>', ) folium.Marker([lat, long], popup=text, icon=xicon).add_to(xmap) folium.Marker([lat, long], popup=text, icon=xicon1).add_to(xmap) return xmap except Exception as e: self.err(e, self._marker, "Can not get marker")
def plot_map(df, center=(-7.2732, 112.7208), show_nums=True, show_seeds=True): m = folium.Map(location=[*center], width=686, height=686, zoom_start=12, api_key='6NbtVc32EkZBkf8eXLAE') for lat, lon, color, poly, jml, kode in df[[ "lat", "lng", "colors", "polygons", "jml", "kode" ]].values: points = to_convex(np.flip(poly).tolist()) vlayer = vector_layers.Polygon( points, fill=True, color="black", fill_color="rgba({}, {}, {}, {})".format(*color), weight=1) m.add_child(vlayer) if show_seeds: clayer = vector_layers.Circle([lat, lon], 2, color="black") m.add_child(clayer) if show_nums: folium.Marker( (lat, lon), icon=DivIcon( icon_size=(.1, .1), icon_anchor=(6, 0), html='<div style="font-size: 8pt; color : black">%s</div>' % str(kode[3:]), )).add_to(m) return m
def create_map(data): # get average coordinates avg_lat = data['lat'].mean() avg_lon = data['lon'].mean() # add color column color = {'producer': '#ff0000', 'consumer': ' #00ff00', 'split': '#000000'} data = (data.assign(node_color=data['node_type']) .replace({'node_color': color})) # create map m = fo.Map(location=[avg_lat, avg_lon], zoom_start=8) for i in range(0, len(data)): # draw colorful circles fo.CircleMarker([data['lat'][i], data['lon'][i]], radius=20, # popup=data['node_id'][i], color=data['node_color'][i], fill_color=data['node_color'][i]).add_to(m) # draw node ids fo.Marker([data['lat'][i], data['lon'][i]], icon=DivIcon(icon_size=(20, 30), icon_anchor=(0, 0), html='<div style="font-size: 16pt">%s</div>' % data['node_id'][i])).add_to(m) return m
def tencent_marker_with_number(out_dir="../../out"): """腾讯地图,marker 上标记数字""" map_osm = folium.Map(location=[31.32, 120.63], zoom_start=12, subdomains="012") locs = [ [31.387113, 120.929393], [31.364861, 120.609265], [31.226864, 120.511118], [31.269273, 120.750024], [31.264751, 120.598769], [31.299345, 120.742185], ] for loc in locs: value = random.randint(0, 100) # 字符 folium.Marker( loc, icon=DivIcon( icon_size=(150, 36), icon_anchor=(7, 20), html='<div style="font-size: 18pt; color : black">{}</div>'. format(value), )).add_to(map_osm) # 圆圈 map_osm.add_child(folium.CircleMarker(loc, radius=20)) file_path = "{}/tencent_marker_with_number.html".format(out_dir) map_osm.save(file_path)
def _create_map(self, data, legende): # On crée une carte initialement centrée sur Strasbourg fmap = folium.Map(self.STRASBOURG_COORD, zoom_start=11, tiles='cartodbpositron') # On ajoute les données des quartiers folium.GeoJson(self.quartiers).add_to(fmap) folium.Choropleth(geo_data=self.quartiers, data=data, key_on='feature.properties.QUARTIER', fill_color='YlGn', fill_opacity=0.5, line_opacity=0.2, legend_name=legende).add_to(fmap) for idx, row in self.quartiers.iterrows(): nom = '<br>'.join(row["QUARTIER"].title().split()) html_div = f'<div style="font-size: 7pt">{nom}</div>' folium.map.Marker((row['coords'][1], row['coords'][0]), icon=DivIcon(icon_size=(150, 36), icon_anchor=(0, 0), html=html_div)).add_to(fmap) display(fmap)
def plotAcc(point): if point['Road_Surfa'] == 'Dry': carcolor = 'brown' fgroup = feature_group7 elif point['Road_Surfa'] == 'Wet/Damp': carcolor = 'blue' fgroup = feature_group6 else: carcolor = 'gray' fgroup = feature_group8 if point['Overall_co'] == 'Fatal': size = 11 elif point['Overall_co'] == 'Serious': size = 9 elif point['Overall_co'] == 'Slight': size = 7 folium.Marker( [point['X1'], point['Y1']], radius=4, icon=DivIcon( icon_size=(20,20), #icon_anchor=(7,20), html='<div style="font-size: %spt; font-weight: bold; color : %s">▣</div>' % (size, carcolor), ) #icon=folium.Icon( #icon_color=carcolor, #icon='glyphicon-certificate', # icon code from above link #),#prefix='fa'), # note fa prefix flag to use Font Awesome ).add_to(fgroup)
def map_day(occ_df, jour): linear = color_scale(occ_df) occ_map = occ_df[occ_df['date'] == jour] map_int4 = folium.Map(location = [43.8, 2.5], zoom_start = 7.5, tiles = 'Stamen Terrain') for i in range(0, len(occ_map)): text = str(occ_map.date.iloc[1]) folium.Circle( location = [occ_map.iloc[i]['Y'], occ_map.iloc[i]['X']], popup = occ_map.iloc[i]['nom_station'], radius = 300 * occ_map.iloc[i]['valeur'], color = 'black', fill = True, fill_color = linear(occ_map.iloc[i]['standard']), fill_opacity = 0.5, opacity = 0.4, ).add_to(map_int4) folium.map.Marker( [44.8, 3.8], icon=DivIcon( icon_size=(200,100), icon_anchor=(0,0), html='<div style="font-size: 24pt">' + text + '</div>', ) ).add_to(map_int4) return(map_int4)
def initMap(is_rob_turn, rob_cur_node, cops_cur_node): # global node_df # Create map, 지도 중심 금정구청으로 잡음 m = folium.Map(location=[node_df.loc[rob_cur_node, 'latitude'], node_df.loc[rob_cur_node, 'longitude']], zoom_start=15) # draw graph on map for row_index, row in node_df.iterrows(): enode_list = row['linkedNode'] for enode in enode_list: fnode_point = [row['latitude'], row['longitude']] enode_point = [node_df.loc[enode, 'latitude'], node_df.loc[enode, 'longitude']] folium.PolyLine([fnode_point, enode_point]).add_to(m) # Show nodes that can be moved by a thief. if is_rob_turn: for i in range(0, len(node_df.loc[rob_cur_node, 'linkedNode'])): linked_node_id = node_df.loc[rob_cur_node, 'linkedNode'][i] folium.Marker([node_df.loc[linked_node_id, 'latitude'], node_df.loc[linked_node_id, 'longitude']], icon=DivIcon( icon_size=(150,36), icon_anchor=(7,20), html='<div style="background-color: white; width:25px; height:25px; border-radius:50%; text-align:center; line-height:25px; font-size:15px;">' +(i).__str__()+'</div>', )).add_to(m) # Show Cop and Robber location folium.Marker([node_df.loc[rob_cur_node, 'latitude'], node_df.loc[rob_cur_node, 'longitude']], icon=folium.Icon(icon='car', prefix='fa', color = 'red')).add_to(m) for i in range(0, cop_num): folium.Marker([node_df.loc[cops_cur_node[i], 'latitude'], node_df.loc[cops_cur_node[i], 'longitude']], icon=folium.Icon(icon='star', color = 'blue')).add_to(m) # Get html representation of map m = m._repr_html_() return m
def add_text(self, location, text, risk): folium.Marker( location, icon=DivIcon( icon_size=(20, 20), icon_anchor=(0, 0), html='<div style="font-size: 20pt; color: %s">%s</div>' % (cmap(risk), text))).add_to(self.base_map)
def create_map(clean_data): # Initialize variables geo_neighborhoods = clean_data[0] positive_cases_by_neighborhood_only_known_names = clean_data[1] positive_cases_no_information_neighborhoods = clean_data[2] deaths_no_information_neighborhoods = clean_data[3] positive_cases_total = clean_data[4] deaths_total = clean_data[5] # Create folium map map = folium.Map(location=[-3.7981414, -38.5218430], zoom_start=12) choropleth = folium.Choropleth( geo_data=geo_neighborhoods, name='choropleth', data=positive_cases_by_neighborhood_only_known_names, columns=['codigoPaciente'], key_on='feature.properties.NOME', fill_color='YlOrRd', fill_opacity=0.6, line_opacity=0.2, highlight=True, legend_name='Casos confirmados de Covid-19 em Fortaleza-CE' ).add_to(map) choropleth.geojson.add_child(folium.features.GeoJsonTooltip(fields=['NOME', 'CASOS_POSITIVOS', 'OBITOS_CONFIRMADOS'], aliases=['Bairro:', 'Casos confirmados:', 'Óbitos confirmados:'])) folium.map.Marker( [-3.68, -38.5399999], icon=DivIcon( icon_size=(150,100), icon_anchor=(0,0), html=f'<div style="font-size:10px;">Bairro: NÃO INFORMADO<br> Casos Confirmados: {positive_cases_no_information_neighborhoods}<br>Óbitos Confirmados: {deaths_no_information_neighborhoods}</div>', ) ).add_to(map) folium.map.Marker( [-3.7, -38.3999999], icon=DivIcon( icon_size=(400,300), icon_anchor=(0,0), html=f'<div style="font-size:20px;font-weight:bold">Total de Casos Confirmados: {positive_cases_total}<br>Total de Óbitos Confirmados: {deaths_total}</div>', ) ).add_to(map) map.save('Covid-19_confirmed_cases_fortaleza.html')
def draw_rexburg_map(corners=CORNERS, zoom_start=13, border=True, grid=True, grid_size=1, grid_numbers=False, circles=False, grid_radius=None): rexburg_map = folium.Map(location=MAP_CENTER, zoom_start=zoom_start) if grid_radius is None: grid_radius = calc_grid_radius(grid_size) if grid_numbers or grid: grid_squares = grid_square_bounds(grid_size) if grid_numbers or circles: grid_centers = calc_grid_centers(grid_size) if border: folium.Rectangle([each for each in corners[::2]], color='gray', weight=2).add_to(rexburg_map) if grid: for row in grid_squares: for square in row: folium.Rectangle(square, fill=False, weight=0.5, color='gray').add_to(rexburg_map) if grid_numbers: counter = 1 for row in grid_squares: for square in row: folium.map.Marker( [ grid_centers[counter - 1][0], grid_centers[counter - 1][1] ], icon=DivIcon( icon_size=(1, 1), icon_anchor=(5, 5), html=f'<div style="text-align:center;font-size:6pt"' f'>{counter}</div>')).add_to(rexburg_map) counter += 1 if circles: for lat, long in grid_centers: folium.Circle([lat, long], radius=grid_radius, fill=True, fill_opacity=0.2, weight=0.3).add_to(rexburg_map) return rexburg_map
def GetText(location , text): return folium.map.Marker( location, icon=DivIcon( icon_size=(150,36), icon_anchor=(0,0), html='<div class="folium-text">{0}</div>'.format(text), ) )
def voronoi_dots(center=(-7.2732, 112.7208)): clusters = pd.read_csv("data/siswa_centroids_voronoi.csv") siswas = pd.read_csv("data/siswa_colored.csv") for lat, lon, color, poly, jml, kode in clusters[[ "lat", "lng", "colors", "polygons", "jml", "kode" ]].values: print(kode) m = folium.Map(location=[*center], width=686, height=686, zoom_start=12, api_key='6NbtVc32EkZBkf8eXLAE') color = literal_eval(color) poly = literal_eval(poly) points = to_convex(np.flip(poly).tolist()) vlayer = vector_layers.Polygon( points, fill=True, color="black", fill_color="rgba({}, {}, {}, {})".format(*color), weight=1) m.add_child(vlayer) siswabysek = siswas.loc[siswas['class'] == int(kode[3:])] dist = 0 for lat2, lon2, classified in siswabysek[["lat", "lng", "class"]].values: clayer = vector_layers.Circle([lat2, lon2], 1, color="red") m.add_child(clayer) cur_dist = calculateDistance(lat, lat2, lon, lon2) if (dist < cur_dist): dist = cur_dist clayer = vector_layers.Circle([lat, lon], 2, color="black") m.add_child(clayer) folium.Marker( (lat, lon), icon=DivIcon( icon_size=(.1, .1), icon_anchor=(6, 0), html='<div style="font-size: 8pt; color : black">%s</div>' % str(kode[3:]), )).add_to(m) clayer = vector_layers.Circle([lat, lon], dist, color="black") m.add_child(clayer) show_map(m, "sekolah/" + kode + ".png")
def add_marker(call_id, coord_num): tooltip = call_id #marker = folium.Marker(location=coord_num, tooltip=tooltip).add_to(folium_map) marker = folium.map.Marker( coord_num, icon=DivIcon( icon_size=(100,36), icon_anchor=(0,0), html='<div style="font-size: 12pt; color: blue;">'+ tooltip + '</div>', ) ).add_to(folium_map)
def route_price(): if request.method == 'GET': return render_template('index.html', header=HEADER_INIT_TEXT), 200 if request.method == 'POST': # Input data processing area = float(request.form['area']) input_address = str(request.form['address']) long, lat, region = get_coords('Москва, '+input_address) # Check for Moscow address if region != 'Москва': print(NOT_MOSCOW) not_moscow = 'Москва (а не %s!), ' %region return render_template('index.html', header=HEADER_TEXT_FARFARAWAY, not_mos=not_moscow), 200 else: # Distance between address and Moscow city center (km) distance = round(haversine((lat, long), (KREMLIN_LAT, KREMLIN_LONG))) AROUND_KREMLIN = 0.51 # Nobody can live at Kremlin except President # If too close if distance < AROUND_KREMLIN: print(TOO_CLOSE) return render_template('index.html', header=HEADER_TEXT_2CLOSE), 200 # Resulting map else: cost = price_predict(distance, area, lat, long) # Preparing data for the map cost_str = ' %s ₽' % cost dist_str = ' %s км' % distance start_coords = (lat, long) world_map = folium.Map(location=start_coords, zoom_start=16) marker_cluster = MarkerCluster().add_to(world_map) radius = 10 # html variables for folium marker html_base = '<div style="font-size: 20pt; height: 200px; width: 400px; background:#4CAF50">' html_vars = DEFAULT_TEXT+dist_str+' и'+cost_str+'</div>' folium.map.Marker([lat, long], icon=DivIcon( icon_size=(150,36), icon_anchor=(0,0), html=html_base+html_vars )).add_to(world_map) folium.Marker(location = [lat, long], radius=radius, popup=[DEFAULT_TEXT+dist_str+cost_str], fill =True).add_to(marker_cluster) # Result map assemble return world_map._repr_html_(), 200
def run(self, day): m = folium.Map([36.4, 128], zoom_start=8) # Draw region titles for name, loc in loc_dict.items(): folium.map.Marker( [loc[0], loc[1]], icon=DivIcon( icon_size=(10,36), icon_anchor=(150, 15), html=f'<div style="font-size: 10pt; border-radius: 5px; background: #7f7fff; color: white; padding: 0px;' f'border: 1px; opacity: 0.8; text-align: center; vertical-align: middle; width: 150px; height: 20px;">{name}</div>', ) ).add_to(m) # Draw region points for name, loc in loc_dict.items(): folium.map.Marker( [loc[0], loc[1]], icon=DivIcon( icon_size=(10,36), icon_anchor=(15,15), html=f'<span style="height: 30px; width: 30px; opacity: 0.8; background-color: #4c4cff; border-radius: 50%; display: inline-block;"></span>', ) ).add_to(m) converted_day = datetime.datetime.strptime(day, "%m/%d/%Y").strftime('%Y-%m-%d') df_day = time_province[time_province['date'] == converted_day] for index, row in df_day.iterrows(): province = row['province'] confirmed = row['confirmed'] print(province, confirmed) # Draw route between regions folium.Circle([loc_dict[province][0], loc_dict[province][1]], radius=log(confirmed+1)*5000, color='red', fillOpacity=0.5, fill=True).add_to(m) day = day.replace('/', '_') m.save(f'output/confirmed_{day}.html')
def plotDot(point_row, fixed_radius, nbd_or_grp): """ This function adds elements to this_map. It adds CircleMarkers with fixed or varying radius It also creates circles with tooltips A text indicating the count is added close to the circle Args : point_row - a row of data expected to contain following columns a) latitude b) longitude c) neighbourhood_cleansed or neighbourhood_group_cleansed d) glow_marker_color Returns : Folium map with circles added """ if fixed_radius: radius = 30 else: radius = point_row["nbd_count_normalized"] if nbd_or_grp == "neighbourhood": text = f'{point_row["neighbourhood_cleansed"]}' else: text = f'{point_row["neighbourhood_group_cleansed"]}' folium.CircleMarker( location=[point_row["latitude"], point_row["longitude"]], radius=radius, # radius=15, weight=3, # color=point_row["glow_marker_color"], # fill_color=point_row["glow_marker_color"], color=dashboard_colors["medium-blue-grey"], fill_color=dashboard_colors["medium-blue-grey"], fill_opacity=0.5, ).add_child(folium.Tooltip( f"{point_row.name}: {text}", )).add_to(this_map) # Add text of count within circle folium.map.Marker( [point_row["latitude"], point_row["longitude"]], icon=DivIcon( icon_size=(150, 36), icon_anchor=(0, 0), html= '<div style="font-size: 12pt; font-weight:bold;color=red">%s</div>' % text, ), ).add_to(this_map) return
def plotDot(point): '''input: series that contains a numeric named latitude and a numeric named longitude this function creates a CircleMarker and adds it to your this_map''' folium.Marker( location=[point.latitude, point.longitude], radius=2, weight=5, icon=DivIcon( html= '<img alt="Police Icon of Colored Outline style - Available in SVG, PNG, EPS, AI & Icon fonts" class="n3VNCb" src="https://cdn.iconscout.com/icon/premium/png-256-thumb/police-1623568-1375513.png" data-noaft="1" jsname="HiaYvf" jsaction="load:XAeZkd;" style="width: 35px; height: 35px; margin: 0px;">', icon_size=(1, 1), icon_anchor=(0, 0), )).add_to(this_map)
def apply_magnitude_markers(self, map): magnitude_markers = folium.FeatureGroup(name='Magnitude markers') map.add_child(magnitude_markers) for earthquake in self.earthquake_data_clean: earthquake_location = (earthquake["latitude"], earthquake["longitude"]) folium.Marker( earthquake_location, icon=DivIcon( icon_size=(150, 36), icon_anchor=(0, 0), html='<div style="font-size: 10pt; color: grey">%s</div>' % earthquake['magnitude'])).add_to(magnitude_markers)
def addlayer(dictobject): for geodata in dictobject: fg = folium.FeatureGroup(name=geodata) local = dictobject[geodata] for geo, traffic15, totPop, trafCapita, countyname, name in zip(local.geometry, local['2015Traffic'], local['Total Population'], local['TrafficperCapita'], local['NAMELSAD'], local['CountyName']): folium.Marker([geo.centroid.y+0.03, geo.centroid.x-0.1], icon=DivIcon(icon_size=(7,12), icon_anchor=(0,0), popup_anchor=(0, 0), html=f'<div style="font-size:5pt; font-family:helvetica neue; text-align:center"><b>{name}</b></div>'), popup=f"{'<br>'.join([countyname, 'Average Daily Traffic: '+'''{:3,.0f}'''.format(traffic15),'Total Population: '+'''{:3,.0f}'''.format(totPop), 'Traffic per Capita: '+'''%3.0f'''%trafCapita])}" ).add_to(fg) # folium.map.Marker([geo.centroid.y, geo.centroid.x], # icon=DivIcon(icon_size=(50, 150), icon_anchor=(30, 0), popup_anchor=(50, 0), # html=f'<div style="font-size:6pt; font-family:helvetica neue; text-align:center"><b>{name}</b></div>'), # ).add_to(fg) fg.add_to(m)
def error_temp(lat_s, long_s, lat_t, long_t, message): """ Returns a blank map when the lat and long not in database. """ start_coords = (float(lat_s), float(long_s)) folium_map = folium.Map(location=start_coords, zoom_start=14) folium.Marker([float(lat_s), float(long_s)], popup='<i>Start</i>').add_to(folium_map) folium.Marker([float(lat_t), float(long_t)], popup='<b>End</b>').add_to(folium_map) folium.map.Marker([float(lat_s), float(long_s)],\ icon=DivIcon(icon_size=(120,22),icon_anchor=(0,0),html='<div style="font-size: 24pt">{}</div>'.format(message),) ).add_to(folium_map) return folium_map.get_root().render()
def make_ldn_map(coord1=[51.476852, -0.000500], coord2=[51.509865, -0.118092], coord3=[51.457331504, -0.109666228]): ldn = [51.506949, -0.122876] m = folium.Map(width='100%', height=480, location=ldn) if not coord1 and not coord2 and not coord3: m.save('london.html') return 'london.html' else: p1 = tuple(coord1) folium.Marker(p1, icon=DivIcon( icon_size=(150, 36), icon_anchor=(7, 20), html='<div style="font-size: 20pt; color : white; font-family: arial">1</div>', )).add_to(m) m.add_child(folium.CircleMarker(p1, radius=15, fill=True, fill_opacity=0.8)) p2 = tuple(coord2) folium.Marker(p2, icon=DivIcon( icon_size=(150, 36), icon_anchor=(7, 20), html='<div style="font-size: 20pt; color : white; font-family: arial">2</div>', )).add_to(m) m.add_child(folium.CircleMarker(p2, radius=15, fill=True, fill_opacity=0.8)) p3 = tuple(coord3) folium.Marker(p3, icon=DivIcon( icon_size=(150, 36), icon_anchor=(7, 20), html='<div style="font-size: 20pt; color : white; font-family: arial">3</div>', )).add_to(m) m.add_child(folium.CircleMarker(p3, radius=15, fill=True, fill_opacity=0.8)) m.save('london.html') return 'london.html'
def plot_map2(center=(-7.2732, 112.7208)): sekolahs = pd.read_csv("data/sekolah.csv") siswas = pd.read_csv("data/siswa_clustered.csv") clusters = pd.read_csv("data/siswa_centroids.csv") # "OpenStreetMap" # "Mapbox Bright" (Limited levels of zoom for free tiles) # "Mapbox Control Room" (Limited levels of zoom for free tiles) # "Stamen" (Terrain, Toner, and Watercolor) # "Cloudmade" (Must pass API key) # "Mapbox" (Must pass API key) # "CartoDB" (positron and dark_matter) m = folium.Map(location=[*center], width=686, height=686, zoom_start=12, tiles="OpenStreetMap") # api_key='6NbtVc32EkZBkf8eXLAE' for lat, lon, color in siswas[["lat", "lng", "colors"]].values: color = literal_eval(color) clayer = vector_layers.Circle( [lat, lon], 1, color="rgba({}, {}, {}, {})".format(*color)) m.add_child(clayer) for lat, lon in clusters[["lat", "lng"]].values: clayer = vector_layers.Circle([lat, lon], 3, color="red") m.add_child(clayer) for kode, lat, lon, radius in sekolahs[["kode", "lat", "lng", "radius"]].values: # if(int(kode[3:]) == int(smp)): clayer = vector_layers.Circle([lat, lon], 3, color="black") m.add_child(clayer) # clayer = vector_layers.Circle([lat,lon], radius, color="black") # m.add_child(clayer) folium.Marker( (lat, lon), icon=DivIcon( icon_size=(.1, .1), icon_anchor=(6, 0), html='<div style="font-size: 8pt; color : black">%s</div>' % str(kode[3:]), )).add_to(m) return m
def draw(self): # create map m = fol.Map(location=[self.lat.mean(), self.lon.mean()], zoom_start=14) for i in range(0, len(self.node_data)): # draw nodes fol.CircleMarker([self.lat[i], self.lon[i]], # popup=data['node_id'][i], color=self.node_data['node_color'][i], fill_color=self.node_data['node_color'][i], radius=20).add_to(m) # draw node ids fol.Marker( [self.lat[i], self.lon[i]], icon=DivIcon( icon_size=(-35, 75), icon_anchor=(0, 0), html='<div style="font-size: 16pt">%s</div>' % self.node_data.index[i] ) ).add_to(m) for i in range(0, len(self.edge_data)): # linewidth settings lw_avg = self.edge_data['value'].mean() lw = self.edge_data['value'][i] / lw_avg fol.PolyLine(locations=[[self.lat[self.edge_data['from_node'][i]], self.lon[self.edge_data['from_node'][i]]], [self.lat[self.edge_data['to_node'][i]], self.lon[self.edge_data['to_node'][i]]]], color='orange', weight=lw * 3).add_to(m) arrows = self._get_arrows( locations=[[self.lat[self.edge_data['from_node'][i]], self.lon[self.edge_data['from_node'][i]]], [self.lat[self.edge_data['to_node'][i]], self.lon[self.edge_data['to_node'][i]]]], color='orange', n_arrows=3) for arrow in arrows: arrow.add_to(m) return m
def AddTextCounties(mapobj, gdf, popup_field_list): gdf = gpd.GeoDataFrame(gdf,crs={'init': 'epsg:4326'}) gdf['geometry'] = gdf.apply(lambda z: Point(z.geometry.centroid.x, z.geometry.centroid.y), axis=1) marker_cluster = MarkerCluster(name='County Names').add_to(mapobj) # Loop through each record in the GeoDataFrame for i, row in gdf.iterrows(): # Create a string of HTML code used in the IFrame popup # Join together the fields in "popup_field_list" with a linebreak between them label = '<br>'.join([str(row[field]) for field in popup_field_list]) #Change Popup Width to 150% to get all text inside the box #https://python-visualization.github.io/folium/modules.html #https://github.com/python-visualization/folium/issues/970 folium.Marker( location=[row.geometry.y, row.geometry.x], icon=DivIcon(html=f"""<div style="font-family: courier new;font size ="16"; color: 'lightblue'">{"{}".format(label)}</div>""") ).add_to(marker_cluster) return mapobj
def app(df_listings, df_attractions, df_predictions, facilities): st.subheader("Prediction of price for a new listing") st.markdown( "If you are interested in adding a new listing to Airbnb, this tool will help you to find an appropriate price " "for your house according to the demand for the specific neighbourhood and the facilities that you are offering. " "All you have to do is to add the neighbourhood of your choise and the amenities you are planning to provide.") X_test = pd.DataFrame(columns=df_predictions.columns) X_test.loc[len(X_test)] = 0 neighs = df_listings['neighbourhood'].unique() rprt_status = st.sidebar.selectbox("Choose Neighbourhood(*)", neighs) container = st.sidebar.beta_container() all = st.sidebar.checkbox("Select all") if all: selected_options = container.multiselect("Select one or more amenities:", facilities, facilities) else: selected_options = container.multiselect("Select one or more amenities:", facilities) if st.button('Predict the price of your new listing'): geolocator = Nominatim(user_agent="electra") location = geolocator.geocode(rprt_status + ", New York") X_test.distance = haversine(df_attractions, location.latitude, location.longitude) X_test[selected_options] = 1 X_test[rprt_status] = 1 model = RandomForestRegressor(max_depth=8, min_samples_leaf=0.1, min_samples_split=0.1, n_estimators=50) model.fit(df_predictions, df_listings.price.to_numpy()[:, np.newaxis]) y_pred = model.predict(X_test) map_hooray = folium.Map([location.latitude, location.longitude], zoom_start=11, tiles="OpenStreetMap") html = "<font color= \"#225d7a\" face = \"Raleway\" size = \"5\"><strong>Price: {}$</strong></font>".format( str(round(y_pred[0]))) folium.Marker([location.latitude, location.longitude], icon=DivIcon(icon_size=(150, 10), icon_anchor=(60, 20), html=html)).add_to( map_hooray) map_hooray.add_child(folium.CircleMarker([location.latitude, location.longitude], radius=80, color="#428DB2", fill=True, fill_color="#428DB2", )) folium_static(map_hooray, width=1000, height=600)
def do_save_map(args, label, C): try: import folium from folium.features import DivIcon import requests import polyline a = ';'.join([','.join(str(p) for p in ll) for ll in zip(C['start_long'], C['start_lat'])]) base_url = 'http://router.project-osrm.org/route/v1/driving/' url = base_url + a + '?overview=full' r = requests.get(url) out = r.json() points = polyline.decode(out['routes'][0]['geometry']) cost = int(float(out['routes'][0]['distance'] / 1000.0)) duration = out['routes'][0]['duration'] print("Route map distance: {:.1f}, duration: {:.1f}" .format(cost, duration)) # FIXME: unused # legs = out['routes'][0]['legs'] # waypoints = out['waypoints'] map_osm = folium.Map(location=points[0], zoom_start=12) folium.PolyLine(points, color="blue", weight=2.5, opacity=0.5).add_to(map_osm) for idx, sid, lat, lon in C[['segment_id', 'start_lat', 'start_long']].itertuples(index=True): folium.Marker([lat, lon], popup='{0:d}'.format(sid)).add_to(map_osm) html = ('<div style="font-size: 10pt; color: red">{0:d}</div>' .format(idx)) folium.map.Marker([lat, lon], icon=DivIcon(icon_size=(150, 36), icon_anchor=(0, 0), html=html) ).add_to(map_osm) fn, fe = os.path.splitext(args.save_map) fname = "{:s}-{:d}{:s}".format(fn, label, fe) print("Save map HTML to file '{:s}'".format(fname)) map_osm.save(fname) except Exception as e: print("Error: Cannot save map to file ({!s})".format(e))
def add_sector_labels(feature_group, geo_data): # display(geo_data) for ix, sector in geo_data.iterrows(): if sector.geometry is None or sector.polygon is None: continue polygon = geometry.Polygon(sector.geometry) font_size = 'font-size: 9pt' xcolor = 'color : Indigo' xalign = 'text-align:center' folium.map.Marker( (polygon.centroid.y, polygon.centroid.x), icon=DivIcon( icon_size=(150, 36), icon_anchor=(75, 18), html= f'<div style="{font_size}; {xcolor}; {xalign}"> {sector.GeoName}</div>', )).add_to(feature_group)
def plot_choropleth_openstreet(df=df): # Initialize the map: 52.3676° N, 4.9041° E m = folium.Map(location=[52.3676, 4.9041], zoom_start=11) district_count = pd.DataFrame( df.groupby("Stadsdeel").count()["Naam"]).reset_index() district_count = district_count.rename(columns={ "Stadsdeel": "District", "Naam": "Count" }) district_count["text"] = district_count[ "District"] + '<br>' + '<br>' + district_count["Count"].astype( str) + " Sports Providers in the District." # Add the color for the chloropleth: m.choropleth(geo_data=geojson, name='choropleth', data=district_count, columns=['District', 'Count'], key_on='feature.properties.Stadsdeel', fill_color='OrRd', fill_opacity=0.7, line_color="white", legend_name='Number of Sports Providers') folium.LayerControl().add_to(m) for district in geojson["features"]: lon, lat = np.array( district["geometry"]["coordinates"]).mean(axis=1).flatten() name = district["properties"]["Stadsdeel"] folium.map.Marker( [lat, lon], icon=DivIcon( icon_size=(8, 8), icon_anchor=(15, 10), html= f'<div style="font-size: 10pt; text_algnment=center;">{name}</div>', )).add_to(m) return m