def theMap(self, main_html, rel_html, rel_pts_names): tool_tip = 'Show pannel' #목적지 점 찍고 html 만들기 main_pt = [self.lat, self.lon] m = folium.Map(location=main_pt, zoom_start=11) board = folium.map.Popup(html = main_html,\ parse_html = False,\ max_width = '200%') folium.Marker(main_pt, popup=board, tooltip=tool_tip, icon=folium.Icon(color='green', icon='star')).add_to(m) # 주변 장소 팝업 만들기 geo_popUPs = [] for geo_summs in rel_html: geo_htm = geo_summs[0] + geo_summs[1] geo_popUPs.append(folium.map.Popup(html = geo_htm,\ parse_html = False,\ max_width = 350)) # 주변 장소 점 찍기 index = 0 for geo_results in rel_pts_names: #{'이름': (위도, 경도), '이름':(위도, 경도), ...} 이런 형태 folium.Marker(rel_pts_names[geo_results], popup=geo_popUPs[index], tooltip=tool_tip).add_to(m) index += 1 m.add_child( MeasureControl(primary_length_unit='kilometers', primary_area_unit='sqkilometers')) m.save('%s.html' % self.key_city) webbrowser.open_new_tab('%s.html' % self.key_city)
def generate_base_map(gdf): """[summary] creates a base map for use in building Naptan maps. Args: gdf ([geopandas data]): [description] map_name ([str]): [str identify of the map] Returns: [type]: [description] """ gm = folium.Map( location=[gdf["Latitude"].mean(), gdf["Longitude"].mean()], zoom_start=11, prefer_canvas=True, zoom_control=True, control_scale=True, ) # add measure control with km and area return calculations. gm.add_child( MeasureControl( position="bottomright", primary_length_unit="kilometers", secondary_length_unit="miles", secondary_area_unit="acres", primary_area_unit="sqmeters", )) # added lat long pop up for reference folium.LatLngPopup().add_to(gm) # clustering added mc = MarkerCluster().add_to(gm) # add the popups with relevant data for row in gdf.itertuples(): html = f"""<!DOCTYPE html><div class="boxed"> <b>ATCOCode:</b> <i>{row.ATCOCode}</i><br> <b>StopType:</b> <i>{row.StopType}</i><br> <b>StopPoint:</b> <i>{row.StopPoint}</i><br> <b>Coordinates:</b> <i>{row.Latitude}, {row.Longitude}</i><br> <b>Locality_Name:</b> {row.LocalityName}<br> <b>AreaName:</b> <i>{row.AreaName}</i><br> </div> """ # add the markers to the marker cluster. mc.add_child( folium.Marker( location=[row.Latitude, row.Longitude], popup=html, radius=8, icon=folium.Icon(color="green", prefix="fa-", icon="ok-sign"), )) # add layer control. folium.LayerControl(collapsed=False, position="topright").add_to(gm) # get name of the mapped area. map_name = gdf.AreaName.iloc[0] # save the map save_generated_map(mc, map_name=map_name) return gm
def index(): folium_map = folium.Map( location=[ 46.8667, 8.2333 ], # Zentrierung der Karte auf den Mittelpunkt der Schweiz. Ortschaft Sachseln zoom_start=8, tiles= "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}", #Karten Design attr="Tiles © Esri — Esri, DeLorme, NAVTEQ", ) #Koordinaten in Pandas speichern data = pd.DataFrame({ 'lat': [ 47.390434, 47.330769, 47.385849, 47.486614, 47.559601, 46.947922, 46.806403, 46.20222, 47.04057, 46.84986, 47.36493, 47.05048, 46.99179, 46.95805, 46.89611, 47.42391, 47.69732, 47.02076, 47.20791, 47.55776, 46.19278, 46.88042, 46.22739, 46.51600, 47.17242, 47.36667 ], 'lon': [ 8.045701, 9.41104, 9.27884, 7.733427, 7.588576, 7.444608, 7.153656, 6.14569, 9.06804, 9.53287, 7.34453, 8.30635, 6.931000, 8.36609, 8.24531, 9.37477, 8.63493, 8.65414, 7.53714, 8.89893, 9.01703, 8.64441, 7.35559, 6.63282, 8.51745, 8.55000 ], 'name': [ "Aarau", "Appenzell", "Herisau", "Liestal", "Basel", "Bern", "Fribourg", "Genf", "Glarus", "Chur", "Delsberg", "Luzern", "Neuenburg", "Stans", "Sarnen", "Sankt Gallen", "Schaffhausen", "Schwyz", "Solothurn", "Frauenfeld", "Bellinzona", "Altdorf", "Sion", "Lausanne", "Zug", "Zurich" ] }) #Koordinaten für Marker festlegen #Marker setzen for i in range(0, len(data)): folium.Marker( [data.iloc[i]['lat'], data.iloc[i]['lon']], popup=folium.Popup(data.iloc[i]['name'], show=True, sticky=True), tooltip=data.iloc[i]["name"] ).add_to( folium_map ) #Hoovereffekt der den Ortsnamen anzeigt und Marker der permanent ist folium_map.add_child(MeasureControl( )) #Hinzufügen des Plugins, mit dem man die Strecke bemessen kann url = ( 'https://media.licdn.com/mpr/mpr/shrinknp_100_100/AAEAAQAAAAAAAAlgAAAAJGE3OTA4YTdlLTkzZjUtNDFjYy1iZThlLWQ5OTNkYzlhNzM4OQ.jpg' ) FloatImage(url, bottom=5, left=85).add_to(folium_map) folium_map.save( 'templates/map.html' ) #Erzeugung der Map als HTML-Datei, damit man sie mit einem iframe in die Seite einbinden kann return render_template('start1.html') #Anzeigen der Map auf der Startseite
def draw_mult_map(df_a, df_b): m = folium.Map(location=[df_a['lat'].mean(), df_b['long'].mean()], zoom_start=15, control_scale=True) feature_group_estaciones = folium.FeatureGroup( name='Estaciones de Bicicletas') feature_group_tiendas = folium.FeatureGroup(name='bicicleterias') marker_cluster_estaciones = MarkerCluster() marker_cluster_tiendas = MarkerCluster() for row in df_a.iterrows(): marker_estaciones = folium.Marker( location=[row[1]['lat'], row[1]['long']], popup=str(row[1]['nro_est']) + '. ' + str(row[1]['nombre']), icon=folium.Icon(color='green')) marker_cluster_estaciones.add_child(marker_estaciones) for row in df_b.iterrows(): marker_tiendas = folium.Marker( location=[row[1]['lat'], row[1]['long']], popup=row[1]['nombre'], icon=folium.Icon(color='red')) marker_cluster_tiendas.add_child(marker_tiendas) feature_group_estaciones.add_child(marker_cluster_estaciones) feature_group_tiendas.add_child(marker_cluster_tiendas) m.add_child(feature_group_estaciones) m.add_child(feature_group_tiendas) m.add_child(folium.LayerControl()) #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 well_map(self,zoom=10, map_style = 'OpenStreetMap',z_unit='ft', to_crs='EPSG:4326', tooltip=False,popup=True, ax=None): """ Make a Foluim map with the selected well Input: zoom -> (int, float) Initial zoom for folium map map_stule -> (str) Type of map folium Return: w_map -> (folium.Map) Folium map object """ _coord = gpd.GeoDataFrame() z_coef = 0.3048 if z_unit=='ft' else 1 x_coord = self.surf_coord.x y_coord = self.surf_coord.y z_coord = self.surf_coord.z*z_coef if self.surf_coord.has_z==True else self.rte*z_coef shape = self.surf_coord crs = self.crs _w = gpd.GeoDataFrame({'x':[x_coord],'y':[y_coord],'z':[z_coord],'geometry':[shape]}, index=[self.name]) _w.crs = crs _w = _w.to_crs(to_crs) _w['lon'] = _w['geometry'].x _w['lat'] = _w['geometry'].y _coord = _coord.append(_w) center = _coord[['lat','lon']].mean(axis=0) #make the map if ax is None: map_folium = folium.Map( location=(center['lat'],center['lon']), zoom_start=zoom, tiles = map_style) else: assert isinstance(ax,folium.folium.Map) map_folium = ax for i, r in _coord.iterrows(): folium.Marker( [r['lat'],r['lon']], tooltip=f"{i}" if tooltip else None, popup = folium.Popup(html=f"{i}",show=True) if popup else None, icon=folium.Icon(icon='tint', color='green') ).add_to(map_folium) folium.LayerControl().add_to(map_folium) #LocateControl().add_to(map_folium) MeasureControl().add_to(map_folium) MousePosition().add_to(map_folium) return map_folium
def make_map(gdf): gm = folium.Map( location=[gdf["Latitude"].mean(), gdf["Longitude"].mean()], zoom_start=11, prefer_canvas=True, zoom_control=True, control_scale=True, ) # add measure control with km and area return calculations. gm.add_child( MeasureControl( position="bottomright", primary_length_unit="kilometers", secondary_length_unit="miles", secondary_area_unit="acres", primary_area_unit="sqmeters", )) # added lat long pop up for reference folium.LatLngPopup().add_to(gm) # clustering added mc = MarkerCluster().add_to(gm) # add the popups with relevant data for row in gdf.itertuples(): html = f"""<!DOCTYPE html><div class="boxed"> <b>ATCOCode:</b> <i>{row.ATCOCode}</i><br> <b>StopType:</b> <i>{row.StopType}</i><br> <b>StopPoint:</b> <i>{row.StopPoint}</i><br> <b>Coordinates:</b> <i>{row.Latitude}, {row.Longitude}</i><br> <b>Locality_Name:</b> {row.LocalityName}<br> <b>AreaName:</b> <i>{row.AreaName}</i><br> </div> """ # add the markers to the marker cluster. mc.add_child( folium.Marker( location=[row.Latitude, row.Longitude], popup=html, radius=8, icon=folium.Icon(color="green", prefix="fa-", icon="ok-sign"), )) # add layer control. folium.LayerControl(collapsed=False, position="topright").add_to(gm) return gm
def wells_surveys_map(self, wells:list=None,zoom:int=10, map_style:str = 'OpenStreetMap',tooltip:bool=True,popup:bool=False,ax=None,radius=10): """ Make a Foluim map with the selected wells Input: wells -> (list, None) List of wells in the Group to show the matrix. If None, all wells in the group will be selected zoom -> (int, float) Initial zoom for folium map Return: w_map -> (folium.Map) Folium map object """ assert isinstance(wells,(list,type(None))) _coord = self.wells_surveys(wells=wells) _coord = _coord.to_crs('EPSG:4326') _coord['lon'] = _coord['geometry'].x _coord['lat'] = _coord['geometry'].y center = _coord[['lat','lon']].mean(axis=0) #make the map if ax is None: map_folium = folium.Map( location=(center['lat'],center['lon']), zoom_start=zoom, tiles = map_style) else: assert isinstance(ax,folium.folium.Map) map_folium = ax for i, r in _coord.iterrows(): folium.Circle( [r['lat'],r['lon']], tooltip=f"{r['well']} <br>md:{r['md']} <br>tvd:{r['tvd']} <br>tvdss:{r['tvdss']} <br>inc:{r['inc']} " if tooltip else None, popup = folium.Popup(html=f"{r['well']} <br>md:{r['md']} <br>tvd:{r['tvd']} <br>tvdss:{r['tvdss']} <br>inc:{r['inc']} ",show=True,max_width='50%') if popup else None, #icon=folium.Icon(icon='circle',prefix='fa', color='green'), radius=radius ).add_to(map_folium) folium.LayerControl().add_to(map_folium) #LocateControl().add_to(map_folium) MeasureControl().add_to(map_folium) MousePosition().add_to(map_folium) return map_folium
def create_folium(df, coords): address = get_address(coords[1], coords[0]) coords = [coords[1], coords[0]] icons = { 'hostelry': { 'color': "orange", 'iconname': "fa-cutlery" }, 'services': { 'color': "blue", 'iconname': "fa-asterisk" }, 'companies': { 'color': "darkpurple", 'iconname': "fa-building" }, 'events': { 'color': "green", 'iconname': "fa-calendar-o" } } map_folium = folium.Map(coords, width=1000, height=700, zoom_start=17) folium.CircleMarker(coords, radius=9, color="#DA1212").add_to(map_folium) for e in df: for coord in df[e]: if coord != coords: try: folium.Marker(coord, radius=9, icon=folium.Icon(color=icons[e]['color'], prefix='fa', icon=icons[e]['iconname']), fill_color="#F35C50").add_to(map_folium) except: pass map_folium.add_child(MeasureControl()) folium.TileLayer('cartodbpositron').add_to(map_folium) tooltip = 'Click me!' folium.Marker(coords, popup='<i>{}</i>'.format(address), icon=folium.Icon(color='red', prefix='fa', icon="fa-circle"), tooltip=tooltip).add_to(map_folium) return map_folium
def map_aals(data: gpdGeoDataFrame, col: str, colname: str, location: list = [38.9, -77.0], zoom_start: int = 12): """ Create a Folium HeatMap of AAL data. Inputs: col = column name to visualize (e.g. 'FLUV_AAL') colname = more formal, readible alias of col. (e.g. 'Fluvial') location = center coordinates for the Folium map to render. zoom_start = initial level of zoom """ m = folium.Map( location=location, tiles='Stamen Terrain', zoom_start=12, ) pointdata = HeatMap(list( zip(data.geometry.y, data.geometry.x, data[col].values)), min_opacity=0.5, max_val=data[col].values.max(), radius=17, blur=15, max_zoom=1, name='{} Hotspots'.format(colname), show=True, overlay=True, control=True) add_tiles(m) m.add_child(MeasureControl()) m.add_child(pointdata) plugins.Fullscreen(position='topleft', title='Full Screen Mode', title_cancel='Full Screen Mode', force_separate_button=True).add_to(m) folium.LayerControl(collapsed=False).add_to(m) return m
def interactive_grid(centery, centerx, lat, lon, z): url_base = 'http://server.arcgisonline.com/ArcGIS/rest/services/' service = 'World_Imagery/MapServer/tile/{z}/{y}/{x}' tileset = url_base + service folmap = folium.Map(location=[centery, centerx], zoom_start=10) #width=800, height=600, x1, y1 = lat.shape for i in range(0, x1): for ii in range(0, y1): folmap.add_child( folium.CircleMarker(location=[lat[i][ii], lon[i][ii]], radius=1, weight=1, fill=True, color=getColor(z[i][ii]), fill_color=getColor(z[i][ii]), fill_opacity=1)) colormap = branca.colormap.StepColormap(colors=[ '#8000FF', '#5500FF', '#4000FF', '#1500FF', '#0000FF', '#002AFF', '#0055FF', '#0080FF', '#00AAFF', '#00D4FF', '#00FFFF', '#00FFAA', '#00FF80', '#00FF2A', '#2AFF00', '#80FF00', '#AAFF00', '#D4FF00', '#FFFF00', '#FFD400', '#FFAA00', '#FF8000', '#FF6A00', '#FF4000', '#FF2A00', '#FF1500', '#FF0000' ], vmin=-3, vmax=1) #colormap = colormap.to_step(index=[0, 0.5,1,1.5,2,2.5,3,3.5,4,4.5,5]) colormap.caption = 'Elevation (m) at NAVD88' colormap.add_to(folmap) #my_ip = requests.get('http://169.254.169.254/latest/meta-data/public-ipv4').content.decode()a #folium.TileLayer(tiles='http://{}:{}/tile/{{z}}/{{x}}/{{y}}.png', # attr='GeoPySpark', name='NED_SC', overlay=True).add_to(folmap) #folium.add_tiles(folmap) folium.TileLayer(tileset, attr="ESRI", name='imagery').add_to(folmap) folium.LayerControl().add_to(folmap) folmap.add_child(MeasureControl()) return folmap
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 wells_map(self, wells:list=None,zoom=10, map_style = 'OpenStreetMap',tooltip=True,popup=False,ax=None): """ Make a Foluim map with the selected wells Input: wells -> (list, None) List of wells in the Group to show the matrix. If None, all wells in the group will be selected zoom -> (int, float) Initial zoom for folium map Return: w_map -> (folium.Map) Folium map object """ assert isinstance(wells,(list,type(None))) _coord = self.wells_coordinates(wells=wells) center = _coord[['lat','lon']].mean(axis=0) #make the map if ax is None: map_folium = folium.Map( location=(center['lat'],center['lon']), zoom_start=zoom, tiles = map_style) else: assert isinstance(ax,folium.folium.Map) map_folium = ax for i, r in _coord.iterrows(): folium.Marker( [r['lat'],r['lon']], tooltip=f"{i}" if tooltip else None, popup = folium.Popup(html=f"{i}",show=True,max_width='50%') if popup else None, icon=folium.Icon(icon='tint', color='green') ).add_to(map_folium) folium.LayerControl().add_to(map_folium) #LocateControl().add_to(map_folium) MeasureControl().add_to(map_folium) MousePosition().add_to(map_folium) return map_folium
def test_unit(): feature_group = FeatureGroup(name='Teltonika') m = Map( location=[25.09841, 55.16275], zoom_start=2, tiles= 'https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoidGFsazJ0cGMiLCJhIjoiY2ptenozdm0yMWlyNTNwcGhwbzc3dG9rNCJ9.NzVTxRk8eVz6g_BrbjonWg', attr='Mapbox') Marker(location=[25.09955, 55.16263], popup='Mt. Hood Meadows', icon=Icon(icon='dashboard')).add_to(feature_group) Marker(location=[25.10124, 55.16332], popup='Timberline Lodge', icon=Icon(color='green')).add_to(feature_group) Marker(location=[25.10255, 55.16545], popup='''<p>Asset Name: Teltonika</p> <p><img src="https://html-online.com/editor/tinymce4_6_5/plugins/emoticons/img/smiley-cool.gif" alt="cool" /></p> <p>Speed: <span style="color: #ff0000;">12 km/hr</span></p> <p> </p> <p> </p>''', icon=Icon(color='red', icon='screenshot')).add_to(feature_group) m.add_child(LatLngPopup()) feature_group.add_to(m) LayerControl().add_to(m) m.add_child(MeasureControl()) m.save('osm.html')
# 4-3-2. 미니맵 만들기 minimap = plugins.MiniMap() map_cctv.add_child(minimap) # 4-3-4. 히트맵 만들기 from folium.plugins import HeatMap HeatMap(data.tolist()).add_to(map_pplace) # 4-3-5. 마우스 포지션(위도, 경도) 찾기 기능 from folium.plugins import MousePosition MousePosition().add_to(map_pplace) # 4-3-6. 측정도구 기능 from folium.plugins import MeasureControl map_pplace.add_child(MeasureControl()) # 4-3-7. 그림 그리기 기능 (이거 되게 자주 쓰일듯!!!!!!) # export=True 옵션 : 내가 그린 영역을 JSON 파일로 뽑아내줌 # 주의점 : 서브그룹이 많으면 4-3-7에서의 export 기능이 안됨. 직접 돌려보면 알거임. fg = folium.FeatureGroup(name="전체") # 전체그룹 설정 g2 = plugins.FeatureGroupSubGroup(fg, '교통정보수집') g1 = plugins.FeatureGroupSubGroup(fg, '교통단속') # 서브그룹 틀 만들기 from folium.plugins import Draw Draw(export=True).add_to(map_pplace) # 4-3-8. 그룹 만들기 g3 = plugins.FeatureGroupSubGroup(fg, '기타') g4 = plugins.FeatureGroupSubGroup(fg, '생활방범') g5 = plugins.FeatureGroupSubGroup(fg, '쓰레기단속') g6 = plugins.FeatureGroupSubGroup(fg, '어린이보호')
def folium_view(request, *args, **kwargs): #================================================== Model data================================================ data = Webmap.object.all()[:50] m = folium.Map([29, -8.86], tiles='OpenStreetMap', zoom_start=5) html_string = m.get_root().render() test = folium.Html('<b>Hello world</b>', script=True) media_url = settings.MEDIA_ROOT #================================================External data json,gejson ...======================================= #jsondata= './webmap/static/communes.geojson' #commun=geopandas.read_file(jsondata) # ====================================================================Plugins=============================================== #More Tiles folium.TileLayer('Stamen Watercolor').add_to(m) plugins.Fullscreen(position='bottomright', title='Expand me', title_cancel='Exit me', force_separate_button=True).add_to(m) #plugins.Geocoder().add_to(m) plugins.LocateControl(auto_start=False, initial_zoom_level=10).add_to(m) #Measure control m.add_child(MeasureControl(position='topleft')) # Showing coordinates formatter = "function(num) {return L.Util.formatNum(num, 3) + ' º ';};" MousePosition( position='topright', separator=' | ', empty_string='NaN', lng_first=True, num_digits=20, prefix='Coordinates:', lat_formatter=formatter, lng_formatter=formatter, ).add_to(m) ################################################################################################################################################################################################### ############################################################################################################################################################################################# #============================================================LayerGroups names fg = folium.FeatureGroup(name='All groups') m.add_child(fg) g1 = plugins.FeatureGroupSubGroup(fg, 'Group1') m.add_child(g1) g2 = plugins.FeatureGroupSubGroup(fg, 'Group2') m.add_child(g2) #------------ external data group json, geojson ... #extdata = plugins.FeatureGroupSubGroup(fg, 'communes',show=False) #m.add_child(extdata) # ===========================================================filtering using data =========================================================================================================== for y in data: grpopup = "<div class = popupdiv><img class='popupimg' src =" + y.link + '>' + "<br><p class='strong'>" + y.Nom + "</p>" + "<p class='desc'>" + y.Services + "</p></div>" + "<div class= ''>" + y.Description_si_disop + '</div> <br>' + "<span class='fas fa-map-pin'></span> " + y.Adress + '<br>' + "<div class= 'telpop'>" + y.Tel + '</div><br>' grimgurl = media_url + '/' + y.img.name grcustomIcon = folium.features.CustomIcon(grimgurl, icon_size=(30, 30)) #-----------------------------------------Criterea 1 --------------------------------------------------------- if y.Nom == 'jarouub': folium.Marker(location=[y.geom.y, y.geom.x], popup=grpopup, radius=40, icon=grcustomIcon).add_to(g1) #-----------------------------------------Criterea 2 ------------------------------------------------------------- elif y.Nom == 'lol': folium.Marker(location=[y.geom.y, y.geom.x], popup=grpopup, radius=40, icon=grcustomIcon).add_to(g2) #-------------------------For object that meet none of the Criterea ---------------------------------------------- else: folium.Marker(location=[y.geom.y, y.geom.x], popup=grpopup, radius=40, icon=grcustomIcon).add_to(fg) #--------------------------External data group ----------------------------------------------------------------- #folium.GeoJson(commun,name='communes',overlay=False).add_to(extdata) folium.LayerControl(collapsed=True).add_to(m) #==============================================================This to add element inside the template generated by Folium ==================================================================== style_statement = '''<style> .leaflet-control{color:#f9f9f9; background-color:#000c } .leaflet-popup-content {margin: auto auto 10% auto;line-height: 1.4;text-align: center;} .popupimg{width:100%;margin-left:0px} .leaflet-popup-content-wrapper {width: 200px;text-align: center;}.leaflet-container { /* all maps */height: 600px;width: 90%;margin: auto;z-index: 0;}@media(max-width:750px){.leaflet-container{height:500px;width:94%;}}#specialbigmap{height:800px;}/*Resizethe'display_raw'textbox*/.django-leaflet-raw-textarea{width:100%;}.bd-placeholder-img{font-size:1.125rem;text-anchor:middle;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;}@media(min-width:768px){.bd-placeholder-img-lg{font-size:3.5rem;}}.leaflet-container .leaflet-marker-pane img{max-width:none!important;max-height:none!important;border-radius:100%;border-style:double;border-width:0.4rem; border-color:#000}.leaflet-touch .leaflet-control-layers, .leaflet-touch .leaflet-bar{border:1pxsolidrgb(128,128,128);background-clip:padding-box;}.leaflet-popup-content-wrapper, .leaflet-popup-tip{background:#000000e8;color:#9aa3a6;box-shadow:03px14pxrgba(0,0,0,0.9);border-radius:1%;}.leaflet-popup-content{margin:5px19px1px19px;line-height:1.2;} .telpop{font-weight:bold}.servicespop{font-size:1.15rem;font-weight:bold;}.fas{margin-right:3%;color:#096cb1;font-size:medium;}.nompop{font-size:18px;position:relative;}.description{text-align:center;position:static;text-transform:uppercase;}.label{color:#096cb1;font-size:14px;font-family:'Roboto';}.leaflet-container{/*allmaps*/height:600px;width:90%;margin:auto;z-index:0;}@media(max-width:750px){.leaflet-container{height:500px;width:94%;}}#specialbigmap{height:800px;}/*Resizethe'display_raw'textbox*/.django-leaflet-raw-textarea{width:100%;}.bd-placeholder-img{font-size:1.125rem;text-anchor:middle;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;} .leaflet-control-layers-toggle {background-image: url("/static/app/img/layers.png"); background-size: 60%;} .leaflet-touch .leaflet-bar {border: 1px solid rgba(0,0,0,0.1);background-color: #000000b8;} .strong {font-weight: 700;line-height: 1.6;font-size: 1.4rem;text-transform: uppercase;} .leaflet-touch .leaflet-control-layers-toggle {width: 44px;height: 44px;background-color: #000000b8;} .leaflet-touch .leaflet-bar a {border-bottom-left-radius: 2px;border-bottom-right-radius: 2px;border: 1px solid #000;} .strong{} .leaflet-popup-content-wrapper {width: 180px;text-align: center;height: auto;} .desc{} .leaflet-popup-content p {margin: 10px 0;} .popupdiv{} .js-measuringprompt{color: #000 } .leaflet-touch .leaflet-control-measure .leaflet-control-measure-toggle{width: 30px;height: 30px;border-radius: 1px;border: solid 1px #000;} </style>''' #Adding the elements t m.get_root().header.add_child(folium.Element(style_statement)) m m.save('Map/templates/Folium.html') context = {'my_map': m} #=========================================================== Adding Django template tag in the beginning of Webmap template======================================================================== filename = 'Map/templates/webmap.html' line = "{% load staticfiles %} {%load leaflet_tags%} {% leaflet_js%}{% leaflet_css%} <script src='{% static 'leaflet/leaflet/leaflet.js' %}'></script> <link rel='stylesheet' href='{% static 'leaflet/leaflet/leaflet.css' %}'>" with open(filename, 'r+') as f: content = f.read() f.seek(0, 0) f.write(line.rstrip('\r\n') + '\n' + content) return render(request, 'Folium.html', context)
def index(): start_coords = (-15.79340,-47.88232) folium_map = folium.Map(location=start_coords, zoom_start=16) draw = Draw() draw.add_to(folium_map) folium_map.add_child(MeasureControl()) tooltip = 'Click me!' folium.Marker( [-15.796218,-47.872002 ], popup='<i>Estrada Parque Ceilândia, SIA</i>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) folium.Marker( [-15.791077,-47.875543], popup='<b>QSB 12, Taguatinga, Região</b>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) folium.Marker( [-15.787711,-47.878397], popup='<b>Bloco A / B, W1 Sul, SQS 104, Asa Sul</b>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) folium.Marker( [-15.790932,-47.879212], popup='<b>Recanto das Emas, Região Integrada de Desenvol...</b>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) folium.Marker( [-15.793678,-47.880199], popup='<b>Recanto das Emas, Região Integrada de Desenvol...</b>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) folium.Marker( [-15.79628,-47.885885], popup='<b>Recanto das Emas, Região Integrada de Desenvol...</b>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) folium.Marker( [-15.789507,-47.883203], popup='<b>Recanto das Emas, Região Integrada de Desenvol...</b>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) folium.Marker( [-47.887988,-47.887988], popup='<b>Recanto das Emas, Região Integrada de Desenvol...</b>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) folium.Marker( [-15.79436,-47.887602], popup='<b>Recanto das Emas, Região Integrada de Desenvol...</b>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) folium.Marker( [-15.788743,-47.889705], popup='<b>Recanto das Emas, Região Integrada de Desenvol...</b>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) folium.Marker( [-15.788826,-47.89346], popup='<b>Recanto das Emas, Região Integrada de Desenvol...</b>', icon=folium.Icon(color='black',icon='car', prefix='fa'), tooltip=tooltip).add_to(folium_map) formatter = "function(num) {return L.Util.formatNum(num, 3) + ' º ';};" MousePosition( position='topright', separator=' | ', empty_string='NaN', lng_first=True, num_digits=20, prefix='Coordinates:', lat_formatter=formatter, lng_formatter=formatter, ).add_to(folium_map) return folium_map._repr_html_()
app = Flask(__name__) app.config["SECRET_KEY"] = os.getenv('SECRET_KEY') app.config["MONGO_DBNAME"] = 'travel_tracker' app.config["MONGO_URI"] = os.getenv('MONGO_URI') mongo = PyMongo(app) countries = mongo.db.country_post.find() # Generated map map_obj = folium.Map([45, 3], zoom_start=4, tiles="cartodbpositron") # Locates current location plugins.LocateControl().add_to(map_obj) # Measure distance of points map_obj.add_child(MeasureControl()) # Create a full screen map plugins.Fullscreen(position='topright', title='Expand me', title_cancel='Exit me', force_separate_button=True).add_to(map_obj) # Adding data to map fgc = folium.FeatureGroup(name="Top 10 countries to visit") fgr = folium.FeatureGroup(name="Top 10 restaurants of the world") fga = folium.FeatureGroup(name="Top 10 attractions in the world") map_obj.add_child(fgc) map_obj.add_child(fgr) map_obj.add_child(fga)
for point in range(0, dams_location_list_size): folium.Marker(dams_location_list[point], popup=df_damData['Dam'][point]).add_to(map_url) map_url # In[146]: # Now add a measure control to measure the boundries of the dams. We can measure the area of a surface and # keep it within the marker popup from folium.plugins import MeasureControl map_url.add_child(MeasureControl()) map_url # In[156]: # Add Layer Control map_layers = map_points add = '/mapserver/tile/{z}/{y}/{x}' ESRI = dict(World_Ocean_Base='http://services.arcgisonline.com/arcgis/rest/services/Ocean/World_Ocean_Base', World_Navigation_Charts='http://services.arcgisonline.com/arcgis/rest/services/specialty/world_navigation_charts', NatGeo_World_Map='http://services.arcgisonline.com/arcgis/rest/services/NatGeo_World_Map/MapServer/0',
poly_line = TimestampedGeoJson(data={ "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "LineString", "coordinates": coordinates, }, "properties": { "times": time, "style": { "color": "red", "weight": 2 } } } ] }, period="PT1M") poly_line.add_to(map) # Create a tool to measure distance and area tool_measure = MeasureControl() tool_measure.add_to(map) # Create tool to draw something tool_draw = Draw() tool_draw.add_to(map) map.save("Munich_with_points_and_lines_.html")
roads = roads.to_crs(epsg=4326) # reproject to WGS84 RoadsLayer = folium.FeatureGroup(name="Roads") RoadsLayer.add_child(folium.GeoJson(roads, style_function=lambda feature:{ 'fillColor': 'blue', 'fillOpacity': 0.6, 'weight': 4, 'color': 'darkblue' })) wageningenMap.add_child(RoadsLayer) # Create layer, add polyline and add layer to map RouteLayer = folium.FeatureGroup(name="Route from campus to shopping center") polylineLocations = [[51.987384, 5.666505], [51.986899, 5.666848], [51.985501, 5.661650], [51.981741, 5.664579], [51.979521, 5.664321], [51.979455, 5.663795], [51.979078, 5.663753], [51.978761, 5.663023]] RouteLayer.add_child(PolyLine(locations=polylineLocations, popup="Path from Gaia to Shopping Center", color="red", weight=2.5, opacity=1)) wageningenMap.add_child(RouteLayer) # Overlay raster on top of map orthophotoLayer = folium.FeatureGroup(name="Infrared Orthophoto of Wageningen") orthophotoLayer.add_child(ImageOverlay(imageFilename, [[min_lat, min_lon], [max_lat, max_lon]], opacity=0.6)) wageningenMap.add_child(orthophotoLayer) # Add measurement control and layer control wageningenMap.add_child(MeasureControl()) wageningenMap.add_child(folium.LayerControl()) # Visualize map wageningenMap # Jupyter Notebook allows interactive visualization in the Notebook wageningenMap.save('output/wageningenMap.html') # The folium map can be stored as an HTML file and viewed by opening the HTML file
def map( self, width='100%', height='100%', tiles='Cartodb Positron', ignore=[], **kwargs, ): ''' Plot overview map with folium Parameters: ---------- tiles: str tiles used, see `folium.Map?`` - "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) ''' if ignore == 'all': ignore = self._units m = folium.Map( location=[self.lat_mid, self.lon_mid], width=width, height=height, zoom_start=11, tiles=tiles, ) # bathymetric contours contours_geojson = load_bathy_contours() tooltip = folium.GeoJsonTooltip( fields=['title'], aliases=['depth'], ) popup = folium.GeoJsonPopup( fields=['title'], aliases=['depth'], ) #colorscale = branca.colormap.linear.Greys_03.scale(levels[-1],levels[0]) def style_func(feature): return { 'color': feature['properties'] ['stroke'], #colorscale(feature['properties']['level-value']), 'weight': 3, #x['properties']['stroke-width'], #'fillColor': x['properties']['fill'], 'opacity': 1., #'popup': feature['properties']['title'], } folium.GeoJson( contours_geojson, name='geojson', style_function=style_func, tooltip=tooltip, popup=popup, ).add_to(m) # campaign details for uname, u in self.items(): if uname not in ignore: for d in u: folium.Polygon([(d.start.lat, d.start.lon), (d.end.lat, d.end.lon)], tooltip=uname + ' ' + d.label + '<br>' + str(d.start.time) + '<br>' + str(d.end.time), color=cnames[u['color']], dash_array='10 20', opacity=.5).add_to(m) folium.Circle( (d.start.lat, d.start.lon), tooltip=uname + ' ' + d.label + '<br>' + str(d.start.time), radius=2 * 1e2, color=cnames[u['color']], ).add_to(m) folium.Circle( (d.end.lat, d.end.lon), tooltip=uname + ' ' + d.label + '<br>' + str(d.end.time), radius=1e2, color=cnames[u['color']], ).add_to(m) # useful plugins MeasureControl().add_to(m) fmtr_lon = "function(dec) {var min= (dec-Math.round(dec))*60; " \ +"direction = (dec < 0) ? 'W' : 'E'; " \ +"return L.Util.formatNum(dec, 0) + direction + L.Util.formatNum(min, 2);};" fmtr_lat = "function(dec) {var min= (dec-Math.round(dec))*60; " \ +"direction = (dec < 0) ? 'S' : 'N'; " \ +"return L.Util.formatNum(dec, 0) + direction + L.Util.formatNum(min, 2);};" MousePosition(lat_formatter=fmtr_lon, lng_formatter=fmtr_lat).add_to(m) return m
popup='<b>Borehole Located: </b>Here<br></br><b>Location: </b>%s' % (borehole), line_color='#3186cc', fill_color='#8E44AD', fill_opacity=0.4, fill=True).add_to(borehole_cluster) for gsl in good_sensor_locations: print(gsl) folium.Marker(location=gsl).add_to(m) for desal in desalinator_location: folium.Marker(location=desal, popup='Desalinator located here', icon=folium.Icon(color='red', icon='water')).add_to(desal_cluster) folium.GeoJson(state_geo, name="Pipes").add_to(m) # folium.GeoJson(pipes, name="Acoustic Sensors").add_to(m) folium.TileLayer(tiles='Stamen Toner', name="Stamen Toner").add_to(m) folium.TileLayer(tiles='Stamen Terrain', name="Stamen Terrain").add_to(m) folium.LayerControl().add_to(m) m.add_child(MeasureControl()) m.add_child(folium.LatLngPopup()) m.save('map.html') print("Saving the webpage for map....")
def sim_folium_heat(geogridfile, griddatafile): #if os.path.exists(geogridfile): # print( "ok esiste" ) geogrid = gpd.read_file(geogridfile).sort_index() geogrid.id = geogrid.id.astype(int) geogrid['centroid'] = geogrid.to_crs(epsg=3857).geometry.centroid.to_crs( epsg=4326) geogrid['cen_lat'] = [p.y for p in geogrid['centroid']] geogrid['cen_lon'] = [p.x for p in geogrid['centroid']] with open(griddatafile) as gin: griddata = json.load(gin) sim_id = griddata['sim_id'] griddata = griddata['grid_cnt'] griddata = [{ 'timestamp': ts, 'cell_id': int(gid), 'cnt': val, } for ts, cnt in griddata.items() for gid, val in cnt.items()] gridcnt = pd.DataFrame.from_dict(griddata) #gridcnt['norm_cnt'] = (gridcnt.cnt - gridcnt.cnt.min()) / (gridcnt.cnt.max() - gridcnt.cnt.min()) gridcnt['norm_cnt'] = gridcnt.cnt / gridcnt.cnt.max() #print(gridcnt) gridcnt = gridcnt.merge(geogrid[['id', 'cen_lat', 'cen_lon']], left_on='cell_id', right_on='id') time_label = [] data = [] for ts, dfg in gridcnt.groupby('timestamp'): #dt = f"{pd.to_datetime(ts, unit='s').tz_localize('utc').tz_convert('Europe/Rome')}" dt = str( pd.to_datetime( ts, unit='s').tz_localize('utc').tz_convert('Europe/Rome')) time_label.append(dt) data.append(dfg[['cen_lat', 'cen_lon', 'norm_cnt']].values.tolist()) # print(dt, dfg.cnt.sum()) #print(time_label) m = folium.Map(control_scale=True) _radius = 60 if "ubrovnik" in str(geogridfile): _radius = 100 HeatMapWithTime( data=data, index=time_label, radius=_radius, # gradient={'0':'Navy', '0.25':'Blue','0.5':'Green', '0.75':'Yellow', '0.85':'orange','1': 'Red'}, gradient={ '0': 'gray', '0.2': 'Blue', '0.4': 'Green', '0.6': 'Yellow', '0.8': 'orange', '1': 'Red' }, # gradient={0.0: 'blue', 0.1: 'orange', 0.5: 'red'}, min_opacity=0.2, max_opacity=0.6, use_local_extrema=False, display_index=True, auto_play=True, ).add_to(m) MeasureControl().add_to(m) colormap = cm.LinearColormap( colors=['gray', 'Blue', 'Green', 'Yellow', 'orange', 'red'], index=[0, 0.2, 0.4, 0.6, 0.8, 1], # tick_labels=[0, 25, 50, 75, 85, 100], caption='Density of population') m.add_child(colormap) s, w = geogrid[['cen_lat', 'cen_lon']].min() n, e = geogrid[['cen_lat', 'cen_lon']].max() m.fit_bounds([[s, w], [n, e]]) text_save = f'{html_folder}/heatmap_{sim_id}.html' m.save(text_save) print(f'* File saved in: {text_save}')
def predict(): F_date = f1.get() F_crimeclass = v.get() F_predmodel = s.get() f1.delete(0,END) master3.destroy() #Split the date day_list = [7,1,2,3,4,5,6] split_date = F_date.split('-') day = int(split_date[0]) month = int(split_date[1]) year = int(split_date[2]) date = datetime.date(year,month,day) #Previous day prev_date = date + datetime.timedelta(days=-1) prev_day = prev_date.day prev_date_month = prev_date.month prev_date_year = prev_date.year SF_COORDINATES = (37.76, -122.45) #crimedata = pd.read_csv('new_train(kaggledata).csv') crimedata = pd.read_csv('demo.csv') state_geo = 'SFPD.json' crime_count = open('crime_countdata.csv','w') # for speed purposes MAX_RECORDS = 878050 list_of_crimes = ["WARRANTS","OTHER OFFENSES","LARCENY/THEFT","VEHICLE THEFT","VANDALISM","NON-CRIMINAL","ROBBERY","ASSAULT","WEAPON LAWS","BURGLARY","SUSPICIOUS OCC","DRUNKENNESS","FORGERY/COUNTERFEITING","DRUG/NARCOTIC","STOLEN PROPERTY","SECONDARY CODES","TRESPASS","MISSING PERSON","FRAUD","KIDNAPPING","RUNAWAY","DRIVING UNDER THE INFLUENCE","SEX OFFENSES FORCIBLE","PROSTITUTION","DISORDERLY CONDUCT","ARSON","FAMILY OFFENSES","LIQUOR LAWS","BRIBERY","EMBEZZLEMENT","SUICIDE","LOITERING","SEX OFFENSES NON FORCIBLE","EXTORTION","GAMBLING","BAD CHECKS","TREA","RECOVERED VEHICLE","PORNOGRAPHY/OBSCENE MAT"] list_of_pdistrict = ["NORTHERN","PARK","INGLESIDE","BAYVIEW","RICHMOND","CENTRAL","TARAVAL","TENDERLOIN","MISSION","SOUTHERN"] count_of_pdistrict = {"NORTHERN":0,"PARK":0,"INGLESIDE":0,"BAYVIEW":0,"RICHMOND":0,"CENTRAL":0,"TARAVAL":0,"TENDERLOIN":0,"MISSION":0,"SOUTHERN":0} # create empty map zoomed in on San Francisco m = folium.Map(location=SF_COORDINATES, zoom_start=13,tiles='CartoDBPositron') cluster = folium.plugins.MarkerCluster(name="Previous Crimes").add_to(m) # add a marker for every record in the filtered data, use a clustered view for each in crimedata[0:MAX_RECORDS].iterrows(): if ((int(each[1]['Day'])==prev_day) and (int(each[1]['Month'])==prev_date_month) and (int(each[1]['Year'])==prev_date_year)): crime_name = list_of_crimes[int(each[1]['Category'])-1] occ_date = "%s-%s-%s"%(str(prev_day),str(prev_date_month),str(prev_date_year)) pdistrict = list_of_pdistrict[int(each[1]['PdDistrict'])-1] count_of_pdistrict[pdistrict]=(count_of_pdistrict[pdistrict])+1 location = "%s,%s"%(each[1]['Y'],each[1]['X']) folium.Marker(location = [each[1]['Y'],each[1]['X']], popup='<b>Occured date: </b>%s<br></br><b>Crime Type: </b>%s<br></br><b>Police District: </b>%s<br></br><b>Location: </b>%s'%(occ_date,crime_name,pdistrict,location),).add_to(cluster) crime_count.write('PD,Crime_Count\n') for key in count_of_pdistrict: crime_count.write("%s,%s\n"%(key,str(count_of_pdistrict[key]))) crime_count.close() state_data = pd.read_csv('crime_countdata.csv') m.choropleth( geo_data=state_geo, name='choropleth', data=state_data, columns=['PD', 'Crime_Count'], key_on='feature.id', fill_color='Reds', fill_opacity=0.7, line_opacity=0.9, legend_name='Crime Rate' ) non_violent_loc =[[ 37.783003799999996,-122.4124143],[37.77436883,-122.5058834],[37.74491907,-122.47577350000002],[37.71083265,-122.43244650000001],[37.72513804,-122.423327],[37.73015769,-122.37598919999999],[37.75999239,-122.3977468],[37.80087263,-122.4269953],[37.77739182,-122.3976156],[37.77539248,-122.4156581],[37.79149808,-122.40574479999998],[37.79750489,-122.4020426]] violent_loc=[[37.72156474,-122.47318200000001],[37.73511269,-122.4845457],[ 37.73449811,-122.4448541],[37.76978409,-122.449123],[37.77753219,-122.4408795],[37.7299736,-122.3920652],[37.80427189,-122.44827839999999],[37.774598600000004,-122.42589170000001],[37.79243096,-122.3957716],[37.75942275,-122.41905890000001],[37.80618612,-122.41625959999999]] for loc in non_violent_loc: folium.CircleMarker(location=loc, radius=30, popup='<b>Prediction Type: </b>Non-Violent Crime<br></br><b>Location: </b>%s'%(loc), line_color='#3186cc', fill_color='#FFFFFF',fill_opacity=0.7, fill=True).add_to(m) for loc in violent_loc: folium.CircleMarker(location=loc, radius=30, popup='<b>Prediction Type: </b>Violent Crime<br></br><b>Location: </b>%s'%(loc), line_color='#3186cc', fill_color='#000000',fill_opacity=0.7, fill=True).add_to(m) folium.TileLayer(tiles='Stamen Toner',name="Stamen Toner").add_to(m) folium.TileLayer(tiles='Stamen Terrain',name="Stamen Terrain").add_to(m) folium.LayerControl().add_to(m) m.add_child(MeasureControl()) FloatImage(url, bottom=5, left=85).add_to(m) m.save('index.html') print "Saving the webpage for map...." class MyBrowser(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) QWebView.__init__(self) self.ui = BrowserDialog() self.ui.setupUi(self) self.ui.lineEdit.returnPressed.connect(self.loadURL) def loadURL(self): url = self.ui.lineEdit.text() self.ui.qwebview.load(QUrl(url)) self.show() #self.ui.lineEdit.setText("") if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyBrowser() myapp.ui.qwebview.load(QUrl("D:\My Programs + Projects\Crime2Vec - QCRI Internship '18\Main Files\GUI\index.html")) myapp.show() sys.exit(app.exec_())
def generate_map(self, file_name): """Generates a .hmtl map using a given name""" folium.LayerControl().add_to(self._map) self._map.add_child(MeasureControl()) self.map.save(self._maps_path + file_name + '.html')
def seiu(lat, lon, time): print("") # request reverse geocoding r = requests.get( 'https://api.opencagedata.com/geocode/v1/json?q=%s+%s&key=7e95a1a406154911b68bfff0a5bf9c34' % (lat, lon)) results = r.json() where = results['results'][0]['formatted'] print("Your location is:", where) # load csv df_ca = pd.read_csv('supporting documents/Dialysis_CA.csv') df_la = pd.read_csv('supporting documents/Dialysis_LA.csv') df_seiu = pd.read_csv('supporting documents/SEIU_UHW_CA.csv') # handle lat lon as floats df_seiu['lat'] = df_seiu['lat'].astype(float) df_seiu['lon'] = df_seiu['lon'].astype(float) df_ca['lat'] = df_ca['lat'].astype(float) df_ca['lon'] = df_ca['lon'].astype(float) df_la['lat'] = df_la['lat'].astype(float) df_la['lon'] = df_la['lon'].astype(float) # map map = folium.Map(location=[36.7783, -119.4179], tiles='Stamen Toner', zoom_start=5.5) # plugin for MeasureControl map.add_child(MeasureControl()) # float image plugin for logo logo = ('https://i.imgur.com/WTmLCbc.png') justice = ('https://i.imgur.com/mJgkwHV.png') FloatImage(logo, bottom=8, left=4).add_to(map) FloatImage(justice, bottom=.5, left=4).add_to(map) fg = folium.FeatureGroup(name='Heat Map of Dialysis Clinics').add_to(map) heat_df = df_ca[['lat', 'lon']] heat_data = [[row['lat'], row['lon']] for index, row in heat_df.iterrows()] HeatMap(heat_data, radius=15, blur=17).add_to(fg) # clinics in CA clinic_df = df_ca[['lat', 'lon']] clinic_data = [[r['lat'], r['lon']] for i, r in clinic_df.iterrows()] fg_1 = folium.FeatureGroup(name='Dialysis Clinics').add_to(map) marker_cluster = MarkerCluster().add_to(fg_1) for point in range(0, len(clinic_data)): folium.Marker(clinic_data[point], popup='<strong>' + "Facility: " + df_ca['Facility N'][point] + " - Address:" '</strong>' + df_ca['Address Li'][point], icon=folium.Icon(color='beige', icon_color='darkpurple', icon='plus')).add_to(marker_cluster) # SEIU offices seiu_df = df_seiu[['lat', 'lon']] seiu_data = [[r['lat'], r['lon']] for i, r in seiu_df.iterrows()] fg_2 = folium.FeatureGroup(name='SEIU UHW Offices').add_to(map) for point in range(0, len(seiu_data)): folium.Marker(seiu_data[point], popup='<strong>' + "SEIU Office: " + df_seiu['SEIU UHW'][point] + " - Address:" '</strong>' + df_seiu['Address'][point], icon=folium.Icon(color='darkpurple', icon_color='white', icon='heart')).add_to(fg_2) folium.LayerControl(collapsed=False).add_to(map) map.save('MapFinal1.html') # Service Area loc = [[lon, lat]] loc_df = pd.DataFrame(loc, columns=['lon', 'lat']) org_df = loc_df[['lat', 'lon']] org_data = [[r['lat'], r['lon']] for i, r in org_df.iterrows()] map2 = folium.Map(location=[float(lat), float(lon)], tiles='Stamen Toner', zoom_start=11) FloatImage(logo, bottom=8, left=4).add_to(map2) FloatImage(justice, bottom=.5, left=4).add_to(map2) for point in range(0, len(org_data)): folium.Marker(org_data[point], popup='<strong>' "Your Input Location:" + where + '</strong>', icon=folium.Icon(color='darkpurple', icon_color='white', icon='user')).add_to(map2) key = '5b3ce3597851110001cf6248c13297498fc24a73a4067bd7d1a87f7d' clnt = client.Client(key=key) # parameters for isochrones request params_iso = { 'profile': 'driving-car', 'range': [time * 60], 'interval': time * 60 } loc_dict = {'loc': {'location': [lon, lat]}} for name, loc in loc_dict.items(): params_iso['locations'] = [loc['location']] iso = clnt.isochrones(**params_iso) folium.features.GeoJson(iso).add_to(map2) iso_buffer = Polygon(iso['features'][0]['geometry']['coordinates'][0]) folium.features.GeoJson(data=mapping(iso_buffer), name='Drive Time Isochrone', overlay=True).add_to(map2) # reverse lat lon df clinic_r_a = df_ca[['lat', 'lon', 'Address Li', 'Facility N']] clinic_r_a_data = [[r['lon'], r['lat'], r['Address Li'], r['Facility N']] for i, r in clinic_r_a.iterrows()] print("") print("Clinics within" + " " + str(time) + " " + "minute(s) of driving" + ": ") print("") for clinic in clinic_r_a_data: point = Point(clinic) if iso_buffer.contains(point): omglol = clinic[3] + " at " + clinic[2] folium.Marker(list(reversed(point.coords[0])), popup='<strong>' + "Clinics within" + " " + str(time) + " " + "minute(s) of driving" + '</strong>' + ": " + omglol, icon=folium.Icon(color='beige', icon_color='darkpurple', icon='plus')).add_to(map2) params_route = { 'profile': 'driving-car', 'format_out': 'geojson', 'geometry': 'true', 'format': 'geojson', 'instructions': 'true', 'preference': 'recommended' } def style_function(color): return lambda feature: dict(color=color, weight=3, opacity=1) for clinic in clinic_r_a_data: point = Point(clinic) for name, loc in loc_dict.items(): org_coord = loc['location'] if iso_buffer.contains(point): omglol = clinic[3] + " at " + clinic[2] clinic_coord = [clinic[0], clinic[1]] params_route['coordinates'] = [org_coord, clinic_coord] json_route = clnt.directions(**params_route) folium.features.GeoJson( json_route, style_function=style_function("#ffff00")).add_to(map2) folium.Marker(list(reversed(point.coords[0])), popup='<strong>' + "Clinics within" + " " + str(time) + " " + "minute(s) of driving" + '</strong>' + ": " + omglol, icon=folium.Icon(color='beige', icon_color='darkpurple', icon='plus')).add_to(map2) print(omglol) print("Driving distance in minute(s):") print( (json_route['features'][0]['properties']['summary']['duration'] ) / 60) print("") map2.save('MapFinal2.html')
color='red', ).add_to(map_hooray) # Interactive marker (drop a pin on the map) #---------------------------------------------------- #map_hooray.add_child(folium.ClickForMarker(popup="Dave is awesome")) map_hooray.save("C:\\Users\ACER\Desktop\\map_mark2.html") # Interaction with the map - ADD MEASURE DISTANCE TOOL #---------------------------------------------------- map_hooray = folium.Map(location=[51.5074, 0.1278], zoom_start=11) # Adds tool to the top right from folium.plugins import MeasureControl map_hooray.add_child(MeasureControl()) # Fairly obvious I imagine - works best with transparent backgrounds from folium.plugins import FloatImage url = ( 'https://media.licdn.com/mpr/mpr/shrinknp_100_100/AAEAAQAAAAAAAAlgAAAAJGE3OTA4YTdlLTkzZjUtNDFjYy1iZThlLWQ5OTNkYzlhNzM4OQ.jpg' ) FloatImage(url, bottom=5, left=85).add_to(map_hooray) map_hooray.save("C:\\Users\ACER\Desktop\\map_measure.html") #Other marker types #---------------------------------------------------- """ I'm skipping over a few markers to move to more interetsing analysis but it's worth knowing that you can also employ. Polygons are markers that let you choose the shape.
def sim_folium_heat(geogridfile, griddatafile): geogrid = gpd.read_file(geogridfile).sort_index() geogrid.id = geogrid.id.astype(int) geogrid['centroid'] = geogrid.to_crs(epsg=3857).geometry.centroid.to_crs( epsg=4326) geogrid['cen_lat'] = geogrid['centroid'].y geogrid['cen_lon'] = geogrid['centroid'].x #print(geogrid) with open(griddatafile) as gin: griddata = json.load(gin)['grid_cnt'] griddata = [{ 'timestamp': ts, 'cell_id': int(gid), 'cnt': val, } for ts, cnt in griddata.items() for gid, val in cnt.items()] gridcnt = pd.DataFrame.from_dict(griddata) #gridcnt['norm_cnt'] = (gridcnt.cnt - gridcnt.cnt.min()) / (gridcnt.cnt.max() - gridcnt.cnt.min()) gridcnt['norm_cnt'] = gridcnt.cnt / gridcnt.cnt.max() #print(gridcnt) gridcnt = gridcnt.merge(geogrid[['id', 'cen_lat', 'cen_lon']], left_on='cell_id', right_on='id') #print(gridcnt) time_label = [] data = [] for ts, dfg in gridcnt.groupby('timestamp'): dt = str( pd.to_datetime( ts, unit='s').tz_localize('utc').tz_convert('Europe/Rome')) time_label.append(dt) data.append(dfg[['cen_lat', 'cen_lon', 'norm_cnt']].values.tolist()) #print(dt, dfg.cnt.sum()) #print(time_label) #print(data) #exit() m = folium.Map(control_scale=True) HeatMapWithTime( data=data, index=time_label, radius=60, #gradient={0.0: 'blue', 0.1: 'lime', 0.3: 'orange', 0.4: 'red'}, gradient={ 0.0: 'blue', 0.1: 'orange', 0.5: 'red' }, min_opacity=0.2, max_opacity=0.6, use_local_extrema=False, display_index=True, auto_play=True, ).add_to(m) MeasureControl().add_to(m) s, w = geogrid[['cen_lat', 'cen_lon']].min() n, e = geogrid[['cen_lat', 'cen_lon']].max() m.fit_bounds([[s, w], [n, e]]) m.save(griddatafile + '.html')
def add_extra(self): folium.LayerControl().add_to(self.map) self.map.add_child(MeasureControl()) return self
def visualise_stop_clusters(gdf, display_column, map_name): """[summary] use marker clustering to display the large number of nodes, Arguments: df {[geopandas Dataframe]} -- [Naptan locality dataframe] display_column {[pandas series]} -- [] map_name {[type]} -- [the name of the area to visualise.] Returns: [folium map object] -- [description] """ # TODO have each different type of stop be represented by a different # colour/ stop icon symbol for the stop point. Ferries = ['FTD, FER, FBT'] Airports = ['AIR, GAT'] rail_stations = ['RSE, RLY, RPL'] MetroTram = ['TMU, MET, PLT'] bus_stations = ['BCE, BST, BCQ, BCS, MKD'] BusStreet = ['BCT, MKD, CUS, HAR, FLX'] Taxis = ['TXR'] Telcabinet = ['LSE, LCB, LPL'] CarPickup = ['SDA'] stopTypeColours = { "AIR": "red", # airports "GAT": "darkred", # airport entrances # don't use light red, it breaks. "FTD": "green", # ferry entrances "FER": "darkgreen", # ferry access area "FBT": "lightgreen", # ferry bay "RSE": "pink", # railway entrance "RLY": "beige", # railway access area "RPL": "lightgray", # railway pole type "BCE": "blue", # bus entrance "BCT": "lightblue", # bus area "BCQ": "darkblue", # bus bay pole "BCS": "cadetblue", # bus bay pole "TXR": "darkpurple", # taxis "SDA": "purple", # cars drop off pick up "LSE": "black" # telecab } polys = display_locality_polygons(gdf, display_column, map_name) # this makes the map and cluster with relational numbers. m = generate_base_map(gdf) folium.Choropleth(geo_data=polys, data=gdf, columns=['ATCOCode', 'StopType'], legend_name=f'Open Naptan{map_name}', bins=[3, 4, 5, 6, 10], fill_opacity='0.3', fill_color='BuPu', line_opacity=0.3, line_weight='2').add_to(m) mc = MarkerCluster().add_to(m) """ feat_group_active = folium.FeatureGroup(name='Active') feat_group_unactive = folium.FeatureGroup(name='Unactive') marker_cluster_active = MarkerCluster() marker_cluster_unactive = MarkerCluster() """ latitudes = list(gdf.Latitude) longitudes = list(gdf.Longitude) stoppoints = list(gdf.StopPoint) stoptypes = list(gdf.StopType) nptgcodes = list(gdf.NptgLocalityCode) for stoppoint, nptg, stoptype, lat, lon in zip(stoppoints, nptgcodes, stoptypes, latitudes, longitudes): html = f"""<!DOCTYPE html><div class="boxed"> <b>StopPoint</b>: <i>{stoppoint}</i><br> <b>StopType</b>: {stoptype}<br> <b>Locality Code</b>: <i>{nptg}</i><br> </div> """ mc.add_child( folium.Marker(location=[lat, lon], popup=html, icon=folium.Icon(color='red', prefix='fa-', icon='ok-sign'))) # folium.GeoJson(polys, name='Locality Polygons').add_to(m) # to allow easier measurement of distance between stops and nodes, # the below control is supplied to draw a line on the map between two # points to allow easier checking of distances. m.add_child(MeasureControl()) """ Not implemented currently. m.add_child(Search(data=gdf, geom_type='Point', search_label='CommonName')) """ folium.LatLngPopup().add_to(m) # folium.LayerControl('topleft', collapsed=True).add_to(m) try: map_folder = str(os.path.join(Path.home(), "Downloads/Naptan_Maps")) Path(f'{map_folder}').mkdir(parents=True, exist_ok=True) except FileExistsError: print(f"{map_name} map is being created.") else: print("Maps folder has been created") finally: map_dest = f'{map_folder}/{timestr}_{map_name}.html' m.save(map_dest) return m