def plot_stops(folium_map: FoliumMap, clustered: bool = True): """ Plot all the stops onto ``folium_map``. ``clustered`` determines if the stop will be clustered/expanded upon zoom. Could use customized color in the future for better rendering effect. """ if clustered: parent = MarkerCluster().add_to(folium_map) else: parent = folium_map for stop in _stops.get_all_stops(): Marker( stop.coordinate, popup=stop.name, icon=Icon(color="green", icon_color="white", icon="bus", angle=0, prefix="fa") ).add_to(parent)
def show_low_enroll_map(col, save_name, data_stat): geo_path = 'SchoolDistricts.geojson' districts = folium.Map( location=[low_enroll['lat'].mean(), low_enroll['lon'].mean()], zoom_start=10) marker_cluster = MarkerCluster().add_to(districts) for name, row in low_enroll.iterrows(): folium.Marker([row["lat"], row["lon"]], popup=popupname).add_to(marker_cluster) districts.choropleth( geo_data=geo_path, data=data_stat, columns=['school_dist', col], key_on='feature.properties.school_dist', fill_color='YlGn', fill_opacity=0.7, line_opacity=0.2, ) districts.save(save_name)
def all_map(request): data = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv", encoding='utf-8') list1 = [] list2 = [] map = folium.Map([36.5427, 126.9168], zoom_start=10) chung = data[data['발생지시도'].str.contains('충남')] chung_location = chung[['발생지시도', '위도', '경도']] marker_cluster = MarkerCluster().add_to(map) for a in chung_location.index: folium.Marker(location=[chung_location.loc[a, "위도"], chung_location.loc[a, "경도"]], zoom_start=12, popup=chung_location.loc[a, "발생지시도"]).add_to(marker_cluster) list1.append(chung_location.loc[a, "위도"]) list2.append(chung_location.loc[a, "경도"]) amap_html = map.get_root().render() context = {'amap_html': amap_html} return render(request, 'amap.html', context)
def create_location_markers(base_map, locations_df): # hotspots_df has columns ['locid', 'lat', 'lng', 'name', 'num', 'marker_size'] marker_cluster = MarkerCluster(control=False) marker_cluster.add_to(base_map) sub_group = FeatureGroupSubGroup(marker_cluster, name='Observations', control=True, show=True) marker_colors_by_name = assign_marker_colors(locations_df) color_by_sectors = 'cluster_label' in locations_df.columns for index, row in locations_df.iterrows(): hname = row['Name'] marker_color = marker_color_for_cluster(row['cluster_label']) if color_by_sectors else \ marker_colors_by_name.get(hname) marker_size = 1 xpopup = folium.Popup(make_observation_popup_html(row), max_width=600) # pixels marker = folium.Marker( location=[row['latitude'], row['longitude']], popup=xpopup, tooltip=hname, icon=folium.plugins.BeautifyIcon( prefix='fa', icon='binoculars', # icon_shape='rectangle', # icon='twitter', icon_shape='marker', # icon_size=Point(), text_color=marker_colors.get('Yellow', 'HotPink'), # actually icon color background_color=marker_color, border_width=marker_size, border_color=marker_colors.get('Silver', 'HotPink'))) marker.add_to(sub_group) sub_group.add_to(base_map) return None
def map_deaths(lat, lon): """ Автор: Ковязин В. Цель: Функция для построения карты по смертям Вход: dataframe Выход: нет(файл) """ deaths = hand_base.bd['DEATHS'].fillna(0) name = hand_base.bd['Name'] def color_change(deaths): """ Автор: Ковязин В. Цель: Функция, устанавливающая цвета Вход: Int смерти Выход: Строка с цветом """ if deaths < 500: return 'green' if 500 <= deaths < 1000: return 'yellow' if 1000 <= deaths < 2000: return 'red' if deaths > 2000: return 'black' map = folium.Map(location=[-6.2146200, 106.8451300], zoom_start=6, titles="Mapbox bright") marker_cluster = MarkerCluster().add_to(map) for lat1, lon1, deaths, name in zip(lat, lon, deaths, name): folium.Marker(location=[lat1, lon1], radius=9, popup='Name: ' + str(name) + '\n' + 'Deaths: ' + str(deaths), fill_color=color_change(deaths), color="gray", fill_opacity=0.9).add_to(marker_cluster) map.save("../Output/map_deaths.html")
def map_damage(lat, lon): """ Автор: Подкопаева П. Цель: Функция для построения карты по ущербу Вход: dataframe Выход: нет (файл) """ damage = hand_base.bd['DAMAGE_MILLIONS_DOLLARS'].fillna(0) name = hand_base.bd['Name'] def color_change(damage): """ Автор: Подкопаева П. Цель: Функция, устанавливающая цвета Вход: Int ущерб Выход: Строка с цветом """ if damage < 50: return 'green' if 50 <= damage < 100: return 'yellow' if 100 <= damage < 200: return 'red' if damage > 200: return 'black' map = folium.Map(location=[-6.2146200, 106.8451300], zoom_start=6, titles="Mapbox bright") marker_cluster = MarkerCluster().add_to(map) for lat1, lon1, damage, name in zip(lat, lon, damage, name): folium.Marker(location=[lat1, lon1], radius=9, popup='Name: ' + str(name) + '\n' + 'Damage: ' + str(damage), fill_color=color_change(damage), color="gray", fill_opacity=0.9).add_to(marker_cluster) map.save("../Output/map_damage.html")
def map_elevation(lat, lon): """ Автор: Баканов Г. Цель: Функция для построения карты по высоте Вход: dataframe Выход: нет (файл) """ elevation = hand_base.bd['Elevation'] name = hand_base.bd['Name'] def color_change(elevation): """ Автор: Баканов Г. Цель: Функция, устанавливающая цвета Вход: Int высота Выход: Строка с цветом """ if elevation < 500: return 'green' if 500 <= elevation < 1000: return 'yellow' if 1000 <= elevation < 3000: return 'red' if elevation > 3000: return 'black' map = folium.Map(location=[-6.2146200, 106.8451300], zoom_start=6, titles="Mapbox bright") marker_cluster = MarkerCluster().add_to(map) for lat1, lon1, elevation, name in zip(lat, lon, elevation, name): folium.Marker(location=[lat1, lon1], radius=9, popup='Name: ' + str(name) + '\n' + 'Elevation: ' + str(elevation) + " m", fill_color=color_change(elevation), color="gray", fill_opacity=0.9).add_to(marker_cluster) map.save("../Output/map_elevation.html")
def draw_map(df, cluster_marks=True): m = folium.Map(location=[df['lat'].mean(), df['long'].mean()], zoom_start=15, control_scale=True) if cluster_marks == True: mc = MarkerCluster() for row in df.iterrows(): mc.add_child( folium.Marker(location=[row[1]['lat'], row[1]['long']], popup=row[1]['nombre'])) m.add_child(mc) else: for row in df.iterrows(): folium.Marker(location=[row[1]['lat'], row[1]['long']], popup=row[1]['nombre']).add_to(m) #OPTIONAL PLUGGINS #minimaps minimap = MiniMap(toggle_display=True) m.add_child(minimap) #measure tool m.add_child(MeasureControl()) #show de coordinates from cursor position MousePosition().add_to(m) #draw tools draw = Draw(export=True) draw.add_to(m) #full screen Fullscreen(position='topright', title='Expand me', title_cancel='Exit me', force_separate_button=True).add_to(m) return m
def generate_map_cluster(self, style=6, zoom_start=12, include_heat_map: bool = True): """ Generates a map which includes cluster depending on the GIS distances between the different points. The Cluster itself depends on the zooming level :param style: indicates which style of the map to be used :type style: int :param zoom_start: set the initial zoom of the map :type zoom_start: int :param include_heat_map: a flag which indicates if an additional HeatMap shall be added to the Map :type include_heat_map: bool :return: """ self.generate_heat_map( style=style, zoom_start=zoom_start ) if include_heat_map else self._generate_base_map(style, zoom_start) self.map.add_child( MarkerCluster( locations=list(zip(self.data[self.lat], self.data[self.lon]))))
def map_locations(lats, lons, names, stars, full_address): locations = list(zip(lons, lats)) popups = [ '{},\n {},\n Rating = {}'.format(name, full_address, stars) for name, full_address, stars in zip(names, full_address, stars) ] for i in locations: print i from folium.plugins import MarkerCluster m = folium.Map(location=[np.mean(lons), np.mean(lats)], tiles='Cartodb Positron', zoom_start=2) m.add_child(MarkerCluster(locations=locations, popups=popups)) m.save('templates/map.html') print "Done."
def search(request): center = [36.6691961, 127.9295186] m = folium.Map(center, zoom_start=7) marker_cluster = MarkerCluster().add_to(m) data = dict() data['mt_name'] = request.GET['mt_name'] with MongoClient('mongodb://192.168.219.104:27017') as client: db = client.mydb mt_data_list = list(db.mountain.find({})) wt_data_list = list(db.weather.find({})) mt_data_list3 = [] for mt_data, wt_data in zip(mt_data_list,wt_data_list): mt_address_temp = mt_data['mt_address'] mt_address = mt_address_temp.split(" ")[0] if mt_address in mt_data['mt_address']: lat_lon = [mt_data['mt_lat'], mt_data['mt_lon']] pop_text = folium.Html( f"<img src={mt_data['mt_img_path_preview']} width=300px; height=300px;><br>" + f"<a href='detail/{mt_data['mt_num']}/' target='_blank'><b>Mountain : {mt_data['mt_name']}</a><br>" + f"<b>Height : {mt_data['mt_height']}m<br>" + f"<b>Current weather : {wt_data['mt_weather_main']} <br>Current temperature : {wt_data['temp']}°C" , script=True ) pop_up = folium.Popup(pop_text) folium.Marker(lat_lon, popup=pop_up, tooltip=mt_data['mt_name']).add_to(marker_cluster) mt_name_list = [mt_data['mt_name'] for mt_data in mt_data_list] for mt_name in mt_name_list: if data['mt_name'] in mt_name: mt_data_list2 = list(db.mountain.find({"mt_name":mt_name})) for x in mt_data_list2: mt_data_list3.append(x) paginator = Paginator(mt_data_list3,10) page =request.GET.get('page',1) page_data = paginator.get_page(page) m = m._repr_html_() return render(request, 'mt/search.html', context={'page_data':page_data, 'map':m})
def createMapToHtml(df): longitude = [] latitude = [] t = 115 country_daily_vaccination = country_daily_vaccinations(df) for i in (country_daily_vaccination["country"]): mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) if findGeoCord(i) != None: loc = findGeoCord(i) longitude.append(loc.longitude) latitude.append(loc.latitude) print('le temps reste pour créer la map', timer, end="\r") t -= 1 else: longitude.append(np.nan) latitude.append(np.nan) country_daily_vaccination['Longitude'] = longitude country_daily_vaccination['Latitude'] = latitude f = folium.Figure(width=1000, height=500) map = folium.Map(tiles="cartodbpositron", max_bounds=True, min_zoom=1.5).add_to(f) marker_cluster = MarkerCluster().add_to(map) for i in range(len(country_daily_vaccination)): lon = country_daily_vaccination.iloc[i]['Longitude'] lat = country_daily_vaccination.iloc[i]['Latitude'] radius = 5 popup_text = """Country : {}<br> nombre total de vaccinations par jour {}<br>""" popup_text = popup_text.format( country_daily_vaccination.iloc[i]['country'], country_daily_vaccination.iloc[i]['daily_vaccinations']) folium.CircleMarker(location=[lat, lon], radius=radius, popup=popup_text, fill=True).add_to(marker_cluster) map.save('analyse/Map.html') print( 'Fin !, la map.html est créée vous y trouverez dans le dossier analyse ' )
def create_clustered_map(): # create map tweet_map = folium.Map(location=[50, 5], zoom_start=3, tiles='Stamen Terrain') marker_cluster = MarkerCluster().add_to(tweet_map) # get tweet from user timeline and plot them in map for page in Cursor(client.user_timeline, screen_name=user, count=200).pages(16): for status in page: tweet = status._json if tweet['coordinates'] is not None: lng = tweet['coordinates']['coordinates'][0] lat = tweet['coordinates']['coordinates'][1] # prepare popup to show for each marker (content = tweet) html_popup = create_html_popup(lat, lng, tweet) # create markers and add them to the map folium.Marker([lat, lng], popup=html_popup).add_to(marker_cluster) elif tweet['place'] is not None: # relevance-based search by location and name (lat, lng) = geodecode(tweet['place']['full_name']) if lat == 0 and lng == 0: # relevance-based search by different location and name values (lat, lng) = geodecode(tweet['contributors'], ['coordinates']) if lat == 0 and lng == 0: pass # prepare popup to show for each marker (content = tweet) html_popup = create_html_popup(lat, lng, tweet) # create markers and add them to the map folium.Marker([lat, lng], popup=html_popup).add_to(marker_cluster) else: pass tweet_map.save(outputfile)
def generate_map_html(self, data): df = pd.DataFrame(data=data, columns=[ "scientificName", "municipality", "state", "country", "latitude", "longitude", "date" ]) columns = [ "scientificName", "municipality", "state", "country", "date" ] df.drop(columns, axis=1, inplace=True) df.replace('', np.nan, inplace=True) # Drop NaN values from dataframe df = df.dropna(subset=['longitude']) df = df.dropna(subset=['latitude']) # Remove extra padding from column names df.columns = df.columns.str.strip() df.head() map_html = folium.Map( location=[df['latitude'].mean(), df['longitude'].mean()], zoom_start=4) # Cluster markers interactively mc = MarkerCluster() # Creating a Marker for each point in df_sample. for row in df.itertuples(): if (row.latitude != None and row.longitude != None): mc.add_child( folium.Marker(location=[row.latitude, row.longitude])) map_html.add_child(mc) outPath = os.path.dirname(__file__).strip( 'visualizations') + 'templates/visualizations/map.html' map_html.save(outPath)
def add_cluster(tweets_map): """Create a Leaflet MarkerCluster to hold all geo tweets.""" with open(os.path.join(resources_path, "js", "create_cluster_icon.js")) as js_file: create_cluster_icon = js_file.read() log.debug("Creating MarkerCluster...") tweets_cluster = MarkerCluster( control=False, icon_create_function=create_cluster_icon, options={ "showCoverageOnHover": False, "spiderfyDistanceMultiplier": 1.7, "spiderLegPolylineOptions": { "weight": 2, "color": "#1DA1F2", "opacity": 0.5, }, }, ) tweets_map.add_child(tweets_cluster) return tweets_cluster
def createMap(): country_geo = 'world-countries.json' data = pd.read_csv('world_stats.csv') data = data.fillna(0) map = folium.Map(location=[20.5937, 78.9629], zoom_start=3) folium.Marker(location=[19.0760, 72.8777], popup='Welcome to <b>Mumbai</b>', tooltip="Click for more").add_to(map) map.choropleth( geo_data="world-countries.json", data=data, # my dataset columns=[ 'county_code', 'confirmed' ], # zip code is here for matching the geojson zipcode, sales price is the column that changes the color of zipcode areas key_on= 'feature.id', # this path contains zipcodes in str type, this zipcodes should match with our ZIP CODE column fill_color='BuPu', fill_opacity=0.7, line_opacity=0.2, legend_name='Confirmed cases') marker_cluster = MarkerCluster().add_to(map) for i in range(data.shape[0]): location = [data['latitude'][i], data['longitude'][i]] tooltip = "Corona virus cases:{}<br> Total population: {}<br>".format( data["confirmed"][i], data['population'][i]) folium.Marker( location, # adding more details to the popup screen using HTML popup=""" <i>Country: </i> <br> <b>${}</b> <br> <i>Total confirmed cases: </i><b><br>{}</b><br> <i>Total recovered cases: </i><b><br>{}</b><br> <i>Total deaths: </i><b><br>{}</b><br>""".format( data['country'][i], data['confirmed'][i], data['recoverd'][i], data['deaths'][i]), tooltip=tooltip).add_to(marker_cluster) print(os.path.join(BASE_DIR, 'covid-19\email_templates\world_map.html')) map.save(os.path.join(BASE_DIR, 'covid-19\email_templates\world_map.html')) return "map created"
def __init__(self, **kwargs): """ Define base map with aoi centroid focused Args: stops (pandas.DataFrame): stops info stored in dataframe aoi (Polygon|Tuple): geo reference of the aois radius: radius for circle aois, none for polygon savename (str): path for output the map """ self.__slots__ = ['stops', 'aoi', 'radius', 'savename'] self.__dict__.update(kwargs) centroid = self.aoi.centroid self.m = folium.Map(location=[centroid.x, centroid.y], zoom_start=20, tiles='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', attr='<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>') # folium.LayerControl().add_to( self.m ) self.marker_cluster = MarkerCluster(maxClusterRadius=10).add_to(self.m) self.map_stop() self.map_aoi() self.m.save(self.savename)
def add_markers_clustered_pretty_icons(fmap, data_points): def icon_polarity(sentiment): polarity = 'glyphicon glyphicon-hand-right' if sentiment > 0.0: polarity = 'glyphicon glyphicon-thumbs-up' elif sentiment < 0.0: polarity = 'glyphicon glyphicon-thumbs-down' return polarity marker_cluster = MarkerCluster().add_to(fmap) for p in data_points: sentiment = get_sentiment(p['text'], p['lang']) f.Marker( location=(p['longitude'], p['latitude']), popup=f.Popup("lang: {}, retweet: {}, favorited: {}".format( p['lang'], str(p['retweet_count']), str(p['favorite_count']))), icon=f.Icon(icon=icon_polarity(sentiment), color=sentiment_leaflet_palette(sentiment), radius=20), ).add_to(marker_cluster) return fmap
def index(): m = folium.Map(location=[20, 0], zoom_start=3) points = db.select_map_data() MarkerCluster(locations=points).add_to(m) map_html = m._repr_html_() if request.method == 'POST': # TODO: add new point to map in a different color - red or so location = request.form['location'] try: decoded_location = geolocator.geocode(location) db.insert_into_data(location, decoded_location.latitude, decoded_location.longitude) # MarkerCluster(locations=[[decoded_location.latitude, decoded_location.longitude]]).add_to(m) # map_html = m._repr_html_() flash('location successfully added') print('new location: ', location, ', ', decoded_location.latitude, ', ', decoded_location.longitude, ', ', datetime.utcnow()) except AttributeError: flash('location not found, try again') print('location not found') return redirect(url_for('index')) return render_template('base.html', map_=map_html)
def map_builder(friends_location: list) -> object: """ Return a folium Map object with markers on the locations from the given list with names-popups above them. friends_location list should be a list of tuples, where the first element is the twitter nickname and the second is a tuple with user's location coordinates. """ mapa = folium.Map() lat = [x[-1][0] for x in friends_location] lon = [x[-1][1] for x in friends_location] names = [x[0] for x in friends_location] frnds = folium.FeatureGroup(name="Friends Markers") marker_cluster = MarkerCluster().add_to(frnds) for lt, ln, nm in zip(lat, lon, names): folium.Marker( location=[lt, ln], popup=nm, icon=folium.Icon( color='red')).add_to(marker_cluster).add_to(marker_cluster) mapa.add_child(frnds) return mapa
def generate_map_with_clustered_markers(df): """ Generates a map with clustered markers of a number of locations given in a dataframe. """ center = get_center(df) cluster_map = folium.Map( location=center, zoom_start=6, tiles='cartodbpositron') # for a lighter map tiles='Mapbox Bright' marker_cluster = MarkerCluster(name='workshops').add_to(cluster_map) for index, row in df.iterrows(): popup = folium.Popup(str(row['popup']), parse_html=True) folium.CircleMarker(radius=5, location=[row['latitude'], row['longitude']], popup=popup, color='#ff6600', fill=True, fill_color='#ff6600').add_to(marker_cluster) return cluster_map
def work_history(): jobs = WorkHistory.query.order_by(WorkHistory.start_date.desc()).all() start_coords=[45.5584432,-114.5665322] m=folium.Map(location=start_coords,width=750, height=500,zoom_start=6,tiles=None,) folium.raster_layers.TileLayer( tiles='OpenStreetMap', name='Open Street Map').add_to(m) folium.raster_layers.TileLayer( tiles='stamenterrain', name='Terrain').add_to(m) folium.raster_layers.WmsTileLayer( url='https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', layers=None, name='Aerial', attr='ESRI World Imagery', show=False).add_to(m) marker_cluster=MarkerCluster(control=False).add_to(m) for job in jobs: popup=render_template('job_popup.html',name=job.name, title=job.title,url=job.url) folium.Marker([job.lat, job.lon],popup=popup).add_to(marker_cluster) fg=folium.FeatureGroup(name='Work History') folium.LayerControl().add_to(m) m=Markup(m.get_root().render()) return render_template('work_history.html', jobs=jobs, map=m)
def add_point_clusters(mapobj, gdf, popup_field_list): #Create empty lists to contain the point coordinates and the point pop-up information coords, popups = [], [] #Loop through each record in the GeoDataFrame for i, row in gdf.iterrows(): #Append lat and long coordinates to "coords" list coords.append([row.geometry.y, row.geometry.x]) #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([row[field] for field in popup_field_list]) #Append an IFrame that uses the HTML string to the "popups" list popups.append(IFrame(label, width = 300, height = 100)) #Create a Folium feature group for this layer, since we will be displaying multiple layers pt_lyr = folium.FeatureGroup(name = 'pt_lyr') #Add the clustered points of crime locations and popups to this layer pt_lyr.add_child(MarkerCluster(locations = coords, popups = popups)) #Add this point layer to the map object mapobj.add_child(pt_lyr) return mapobj
def map_(): data_geodf=update_req_ep5() m = folium.Map(location=[45.46, 9.19], zoom_start=13) marker_cluster = MarkerCluster().add_to(m) for indice, row in data_geodf.iterrows(): folium.Marker( location=[row["lon"], row["lat"]], popup=row['7_Classify_the_distr'], icon=folium.map.Icon(color='red') ).add_to(marker_cluster) tiles = ['stamenwatercolor', 'cartodbpositron', 'openstreetmap', 'stamenterrain'] for tile in tiles: folium.TileLayer(tile).add_to(m) milano = gpd.read_file("ace_maggio_2011.geojson") csv_milano=pd.read_csv(r"ace_maggio_2011_4326.csv", sep=";") folium.Choropleth(geo_data=milano, name="choropleth", data=csv_milano, columns=["ACE","SUM_POP_20"], key_on="feature.properties.ACE", fill_color="YlGnBu", fill_opacity=0.7, line_opacity=0.2, legend_name="POPULATION", ).add_to(m) folium.LayerControl().add_to(m) m.save('templates/map_outp.html')
def executeMaskMap(): my_info_df = getMaskStoreInfo() data_for_draw = my_info_df.loc[:, ['name', 'latitude', 'longitude']] data_for_draw_except_nan = data_for_draw.dropna() sales_dict = getMaskStoreSalesInfo() my_store_and_sales_info_df = mergeSalesInfobyStoreCode( sales_dict, my_info_df) data_for_draw2 = my_store_and_sales_info_df.loc[:, [ 'name', 'latitude', 'longitude', 'remain_stat' ]] data_for_draw2_nan = data_for_draw2.dropna() # 판매 중지 데이터 없애기 data_for_draw_except_nan2 = data_for_draw2_nan[ data_for_draw2_nan['remain_stat'] != 'break'] map_hs2 = folium.Map((37.3402849, 126.7313189), zoom_start=15) # minimap = plugins.Minimap() # map_hs2.add_child(minimap) mc2 = MarkerCluster() names = list(data_for_draw_except_nan2['name']) latitudes = list(data_for_draw_except_nan2['latitude']) longitudes = list(data_for_draw_except_nan2['longitude']) remain_stats = list(data_for_draw_except_nan2['remain_stat']) for i in tqdm(range(len(names))): mc2.add_child( folium.Marker(location=[latitudes[i], longitudes[i]], icon=folium.Icon(color=color_dic[remain_stats[i]]), tooltip=names[i], popup=names[i] + ' ' + remain_stat_kor[remain_stats[i]])) map_hs2.add_child(mc2) map_hs2.save("./mask_store_total.html")
def pushtoMap(information): cmap = folium.Map( location=[information[0]["latitude"], information[0]["longitude"]], zoom_start=5) for inf in information: try: latitude = inf["latitude"] longitude = inf["longitude"] marker = MarkerCluster().add_to(cmap) folium.Marker(location=[latitude, longitude], icon=folium.Icon(color='blue', icon='info-sign')).add_to(marker) except: continue cmap.save('index.html') # # # # for place in information: # # try: # # print("City: "+ str(place['city'])) # # gcode = geolocator.geocode(place["city"]) # # latitude = gcode.latitude # # longitude = gcode.longitude # # # # folium.Marker(location=[latitude, longitude], # # icon=folium.Icon(color='blue', icon='info-sign')).add_to(marker) # # except: # # print("Error: "+ str(place['city'])) # # continue # # cmap.save('index.html') pass
def map(foodtype): name = foodtype + '.csv' tacos = pd.read_csv(name) gdf = geopandas.GeoDataFrame(tacos, geometry=geopandas.points_from_xy(tacos.longitude, tacos.latitude)) gdf.crs = {'init' :'epsg:4326'} # Get x and y coordinates for each point gdf["x"] = gdf["geometry"].apply(lambda geom: geom.x) gdf["y"] = gdf["geometry"].apply(lambda geom: geom.y) # Create a list of coordinate pairs locations_with_weights = list(zip(gdf["y"], gdf["x"],np.exp(5*(gdf['Weighted taco score 2']-.3)))) locations = list(zip(gdf["y"], gdf["x"])) html = """Resturant Name: <td>{}</td><br> Food Score: <td>{}</td>""".format m = folium.Map(location=[43.65,-79.38], tiles = 'cartodbpositron', zoom_start=11, control_scale=True) width, height = 300,50 popups, locations = [], [] for idx, row in gdf.iterrows(): locations.append([row['geometry'].y, row['geometry'].x]) name = row['name'] iframe = folium.IFrame(html(name,row['Weighted taco score 2']), width=width, height=height) popups.append(folium.Popup(iframe)) h = folium.FeatureGroup(name='Resturant') h.add_child(MarkerCluster(locations=locations, popups=popups)) m.add_child(h) points_gjson = folium.features.GeoJson(gdf, name="Good Tacos") HeatMap(locations_with_weights).add_to(m) m.save('templates/map.html') return render_template('map.html')
def open(self, json_container): cameraInfo = Helper.JsonList(json_container) number = cameraInfo.GetEqualRowsCount("District", ["Дмитровский район"]).GetList()[0][1] dmitrov_camera = cameraInfo.GetWereEqual("District", "Дмитровский район").GetList() map = folium.Map(location=[55.888157, 37.531341], zoom_start = 12) marker_cluster_dr = MarkerCluster().add_to(map) for camera in dmitrov_camera: folium.CircleMarker(location=self.SwupCoordinates(camera["geoData"]["coordinates"]), radius = 8, fill_color="red", color="gray", popup = camera["Address"], fill_opacity = 0.9).add_to(marker_cluster_dr) try: os.mkdir(".\\temp") map.save(".\\temp\\map.html") webbrowser.open('.\\temp\\map.html', new=1) except: self.DeleteTempFolder()
def show_stores_distribution_graph(dataframes): """ Req. 1-3-5 각 음식점의 위치 분포를 지도에 나타냅니다. """ stores = dataframes["stores"] contains = stores["address"].str.contains("강원도", na=False) subset = stores[contains] center = [37.541, 126.986] m = folium.Map(location=center, zoom_start=10) marker_cluster = MarkerCluster().add_to(m) for i, store in subset.iterrows(): folium.Marker(location=[store.latitude, store.longitude], popup=store.store_name, icon=folium.Icon(color='red', icon='ok')).add_to(marker_cluster) if i == 1000: break m.save('./map.html')
def map_builder(film_list: list, user_location: tuple, user_year: int) -> None: """ Built a map with 3 layers and saves it to the '(user_year)_film_map.html' file. """ mapa = folium.Map(location=list(user_location)) lat = [x[-1][0] for x in film_list] lon = [x[-1][1] for x in film_list] names = [x[0] for x in film_list] flm = folium.FeatureGroup(name="Films Marker") lines_loc = folium.FeatureGroup(name="Connected with you") marker_cluster = MarkerCluster().add_to(flm) for lt, ln, nm in zip(lat, lon, names): folium.Marker(location=[lt, ln], popup=nm, icon=folium.Icon(color='red')).add_to(marker_cluster) folium.PolyLine( locations=[list(user_location), [lt, ln]], weight=2).add_to(lines_loc) mapa.add_child(flm) mapa.add_child(lines_loc) folium.LayerControl().add_to(mapa) mapa.save(f'{user_year}_film_map.html')