def garden(request, id): info = get_object_or_404(Garden, pk=id) photos = Photo.objects.filter(garden=info).exclude( id=info.photo.id).order_by("-date")[:12] map = folium.Map( zoom_start=14, scrollWheelZoom=False, location=[info.geometry.centroid[1], info.geometry.centroid[0]], tiles=STREET_TILES, attr="Mapbox", ) folium.GeoJson( info.geometry.geojson, name="geojson", ).add_to(map) Fullscreen().add_to(map) context = { "map": map._repr_html_(), "info": info, "photos": photos, } return render(request, "core/garden.html", context)
def get_main_map(gfd, center_location, tile, color_palette): """ :param gfd: GeoDataframe with filters to show or not in map :param center_location: list with central coordinates :param tile: string with basemap raster tile to show :param color_palette: color_palette to render :return: enables html """ # All layers to add MUST BE EPSG3857 for proyection compatibility print( f"\n-- Rendering Main Map ----------------------------------------------------------------------------------------------" ) m = folium.Map( location=center_location, zoom_start=14, max_zoom=16, min_zoom=13, min_lat=40.15, max_lat=40.75, min_lon=-3.25, max_lon=-3.95, max_bounds=True, control_scale=False, prefer_canvas=True, tiles=tile, ) for i, val in enumerate(gfd.index.tolist()): fillColor = color_palette[i] gjson_popup = folium.features.GeoJsonTooltip(fields=[ 'value', 'currentUse', 'centuryOfConstr', 'nFloors_AG', 'nFloors_BG' ], aliases=[ 'Voting_Mean', 'Main_Use', 'Construction_Age', 'numFloors_aboveGr', 'numFloors_belowGr' ], localize=True, sticky=True) gjson = folium.GeoJson(gfd[gfd.index == val], name=f"cluster_{val}", tooltip=gjson_popup, style_function=lambda x, fillColor=fillColor: { 'fillColor': fillColor, 'color': fillColor, 'weight': 0.2, 'fillOpacity': 0.90 }).add_to(m) Fullscreen().add_to(m) print( f"\t MAIN MAP \tRENDERED --------------------------------------------------------------------------------" ) m.save(f'{MAP_SAVE_PATH}map_to_render.html')
def vegetation_type(request, slug): info = get_object_or_404(VegetationType, slug=slug) if "download" in request.POST: geo = info.spaces.all()[0].geometry response = HttpResponse(geo.geojson, content_type="application/json") response[ "Content-Disposition"] = f"attachment; filename=\"{info.name}.geojson\"" return response map = folium.Map( zoom_start=14, scrollWheelZoom=False, tiles=STREET_TILES, attr="Mapbox", ) Fullscreen().add_to(map) for each in info.spaces.all(): folium.GeoJson( each.geometry.geojson, name="geojson", ).add_to(map) map.fit_bounds(map.get_bounds()) context = { "info": info, "map": map._repr_html_(), } return render(request, "core/vegetationtype.html", context)
def addFullScreen(m): Fullscreen( position='topright', title='Full Screen', title_cancel='Exit', force_separate_button=True ).add_to(m) return m
def main(): connection = get_connection() cursor = connection.cursor(cursor_factory=DictCursor) if '--vbo_id' in sys.argv: index = sys.argv.index('--vbo_id') vbo_id = sys.argv[index + 1] elif '--address' in sys.argv: index = sys.argv.index('--address') address = sys.argv[index + 1] vbo_id = get_vbo_id_of_address(address, cursor) if vbo_id == None: print( 'No vbo_id found for the address, please check your address again. It should be of the form "1234AB_123".' ) return else: raise ValueError( 'You should specify the dwelling using either the --vbo_id or the --address flag.' ) pipeline('--vbo_id', vbo_id) print('\n============\n') dwelling = get_bag_vbo(vbo_id, cursor) buurt_id = dwelling['buurt_id'] x, y = parse_geometry(dwelling['geometry']) lon, lat = rijksdriehoek_to_wsg84(x, y) m = initiate_folium_map(lon, lat) results_cursor = get_buurt_results(buurt_id, cursor) add_markers_to_map(vbo_id, m, results_cursor) fullscreen = Fullscreen() fullscreen.add_to(m) print('Saving map...') current_dir = os.path.dirname(os.path.realpath(__file__)) filename = f"map-{dwelling['adres']}.html" path = os.path.join(current_dir, filename) m.save(path)
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 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
except: print (' > fort.61 does not include wind info ..') wind_stations = False ####################################################### print(' > Put together the final maps') # Here is the final result. Explore the map by clicking on the map features plotted! lon = track.centroid.x lat = track.centroid.y ############################################################ ##################################################################### #if 'FLDATELBL' in points[0].keys(): ## m = folium.Map(location=[lat, lon], tiles='OpenStreetMap', zoom_start=4) Fullscreen(position='topright', force_separate_button=True).add_to(m) print(' > Maxele plot..') contour,MinVal,MaxVal,levels = Read_maxele_return_plot_obj(fgrd=fgrd,felev=felev) gdf = collec_to_gdf(contour) # From link above plt.close('all') ## Get colors in Hex colors_elev = [] for i in range (len(gdf)): color = my_cmap(i / len(gdf)) colors_elev.append( mpl.colors.to_hex(color) ) #assign to geopandas obj gdf['RGBA'] = colors_elev #
@author: hung """ import folium import pandas as pd from folium.plugins import TimestampedGeoJson, MeasureControl, Draw, Fullscreen from numpy.random import random, seed seed(0) map = folium.Map(location=(48.13, 11.57), zoom_start=13, control_scale=True, prefer_canvas=True) # Add fullscreen fs = Fullscreen(position="topleft") fs.add_to(map) lat_init, lon_init = 48.13, 11.57 # München for i in range(10): new_lat, new_lon = lat_init + i * 0.01, lon_init + i * 0.01 point = folium.map.Marker(location=(new_lat, new_lon), popup='Latitude: {}\nLongitude: {}'.format(new_lat, new_lon)) point.add_to(map) lat_init, lon_init = 48.13, 11.58 # München for i in range(10): point = folium.Circle(location=(lat_init + i * 0.01, lon_init + i * 0.01), popup='Point {}'.format(i), radius=50, fill=True, fill_color="b", fill_opacity=1.) point.add_to(map) # Add tool to display line
def well_map(): url = 'https://npdfactpages.npd.no/downloads/shape/wlbPoint.zip' # change path to your local directory urllib.request.urlretrieve(url, 'data/wlbPoint.zip') # change path to your local directory wells_explo = geopandas.read_file('zip://data/wlbPoint.zip', encoding='utf-8') wells_explo['wlbEwDesDeg'] = wells_explo['geometry'].x wells_explo['wlbNsDecDeg'] = wells_explo['geometry'].y wells_explo_sel = wells_explo.filter([ 'wbName', 'well_name', 'discovery', 'field', 'prodLicenc', 'well_type', 'drilOperat', 'entryYear', 'cmplYear', 'content', 'main_area', 'totalDepth', 'age_at_TD', 'fmTD', 'discWelbor', 'geometry', 'wlbEwDesDeg', 'wlbNsDecDeg' ], axis=1) wells_explo_all = wells_explo_sel.loc[wells_explo_sel['well_type'].isin( ['EXPLORATION'])] map_wells = folium.Map(location=[ wells_explo_all['wlbNsDecDeg'].mean(), wells_explo_all['wlbEwDesDeg'].mean() ], zoom_start=5, tiles='cartodbpositron') fs = Fullscreen() # adding an extra map background in the layer menu tile = folium.TileLayer('OpenStreetMap').add_to(map_wells) """ defining parameters for our markers and the popups when clicking on single markers """ callback = ( 'function (row) {' 'var marker = L.marker(new L.LatLng(row[0], row[1]));' 'var icon = L.AwesomeMarkers.icon({' "icon: 'star'," "iconColor: 'black'," "markerColor: 'lightgray'," '});' 'marker.setIcon(icon);' "var popup = L.popup({maxWidth: '300'});" "const display_text = {text: '<b>Name: </b>' + row[2] + '</br>' + '<b> Age at TD: </b>' + row[3]};" "var mytext = $(`<div id='mytext' class='display_text' style='width: 100.0%; height: 100.0%;'> ${display_text.text}</div>`)[0];" "popup.setContent(mytext);" "marker.bindPopup(popup);" 'return marker};') """ creating clusters with FastMarkerCluster """ fmc = FastMarkerCluster( wells_explo_all[['wlbNsDecDeg', 'wlbEwDesDeg', 'wbName', 'age_at_TD']].values.tolist(), callback=callback) fmc.layer_name = 'Exploration Wells' map_wells.add_child(fmc) # adding fastmarkerclusters to map map_wells.add_child(fs) # adding fullscreen button to map folium.LayerControl().add_to(map_wells) # adding layers to map return map_wells._repr_html_()
def load_map(area, datafile, generate_ids, return_html=True): """ Create a map for a bouldering zone that shows the GEOJSON data, names and links to video playlists of its sectors as well as the parking areas. All this data should be provided via a JSON file """ generate_ids.reset_seed() area_data = {} with open(datafile, encoding='utf-8') as data: area_data = json.load(data) area_map = folium.Map( location=[area_data['latitude'], area_data['longitude']], zoom_start=area_data['zoom']) area_map._id = generate_ids.next_id() # reassign id for child in area_map._children.values(): child._id = generate_ids.next_id() tile_layer = folium.TileLayer( tiles= 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', name='Satellite', attr= 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community' ) tile_layer._id = generate_ids.next_id() # reassign id tile_layer.add_to(area_map) # Add fullscreen button to map fs = Fullscreen() fs._id = generate_ids.next_id() fs.add_to(area_map) sectors = area_data['sectors'] # Create a Folium feature group for this layer, since we will be displaying multiple layers sector_lyr = folium.FeatureGroup(name='Zone Markers') sector_lyr._id = generate_ids.next_id() # reassign id for sector in sectors: if not sector['sector_data'] or not sector['link']: continue sector_map = folium.GeoJson( os.path.dirname(os.path.abspath(datafile)) + sector['sector_data'], name=sector['name'], tooltip=sector['name'], style_function=lambda x: { 'color': x['properties']['stroke'], 'weight': x['properties']['stroke-width'], 'opacity': SECTOR_OPACITY, 'fillColor': x['properties']['stroke'], }) sector_map._id = generate_ids.next_id() # reassign id sector_html = utils.js_helpers.generate_sector_html( sector['name'], sector['link']) sector_popup = folium.Popup(sector_html, max_width=POPUP_WIDTH, min_width=POPUP_WIDTH) sector_popup._id = generate_ids.next_id() # reassign id for child in sector_popup._children.values(): child._id = generate_ids.next_id() sector_map.add_child(sector_popup) sector_lyr.add_child(sector_map) # Parking areas for parking in area_data['parkings']: parking_icon = CustomIcon('static/images/icons/parking.png', icon_size=(ICON_SIZE, ICON_SIZE)) parking_icon._id = generate_ids.next_id() # reassign id parking_marker = folium.Marker( location=[ parking['parking_latitude'], parking['parking_longitude'] ], popup=utils.js_helpers.generate_parking_html( [parking['parking_latitude'], parking['parking_longitude']]), tooltip='Parking', icon=parking_icon) parking_marker._id = generate_ids.next_id() # reassign id for child in parking_marker._children.values(): child._id = generate_ids.next_id() sector_lyr.add_child(parking_marker) # Approximation if area_data.get('approximation', None) is not None: import gpxpy import gpxpy.gpx approximation_geojson = { 'type': 'Feature', 'properties': { 'stroke': '#1f1a95', 'stroke-opacity': 1, 'stroke-width': 2 }, 'geometry': { 'type': 'LineString', 'coordinates': [] } } gpx_path = 'data/zones/' + area + '/' + area_data.get('approximation') with open(gpx_path, 'r') as gpx_file: gpx = gpxpy.parse(gpx_file) for track in gpx.tracks: for segment in track.segments: for point in segment.points: approximation_geojson['geometry'][ 'coordinates'].append( [point.longitude, point.latitude]) zone_approximation = folium.GeoJson( approximation_geojson, name='Approximation', tooltip=APPROX_PLACEHOLDER, style_function=lambda x: { 'color': x['properties']['stroke'], 'weight': x['properties']['stroke-width'], 'opacity': SECTOR_OPACITY, 'fillColor': x['properties']['stroke'], }) zone_approximation._id = generate_ids.next_id() # reassign id zone_approx_html = utils.js_helpers.generate_file_download_html( area, area_data.get('approximation'), 'Track') track_popup = folium.Popup(zone_approx_html, max_width=POPUP_WIDTH, min_width=POPUP_WIDTH) track_popup._id = generate_ids.next_id() # reassign id for child in track_popup._children.values(): child._id = generate_ids.next_id() zone_approximation.add_child(track_popup) sector_lyr.add_child(zone_approximation) # Sectors zoomed_out_lyr = folium.FeatureGroup(name='Sector Markers') zoomed_out_lyr._id = generate_ids.next_id() # reassign id zoomed_out_icon = CustomIcon('static/images/marker/marker.png', icon_size=(MARKER_SIZE, MARKER_SIZE)) zoomed_out_icon._id = generate_ids.next_id() # reassign id sectors_marker = folium.Marker( location=[area_data['latitude'], area_data['longitude']], tooltip=area_data['name'], icon=zoomed_out_icon) sectors_marker._id = generate_ids.next_id() # reassign id zoomed_out_lyr.add_child(sectors_marker) area_map.add_child(zoomed_out_lyr) area_map.add_child(sector_lyr) layer_control = folium.LayerControl() layer_control._id = generate_ids.next_id() # reassign id layer_control.add_to(area_map) # Since folium does not support all the functionalities we need # we obtain them by injecting JavaScript code in the map html map_html = area_map.get_root().render() map_html = utils.js_helpers.make_layer_that_hides(map_html, area_map.get_name(), sector_lyr.get_name(), DEFAULT_AREA_ZOOM) map_html = utils.js_helpers.make_layer_that_hides( map_html, area_map.get_name(), zoomed_out_lyr.get_name(), DEFAULT_AREA_ZOOM, False, True) # Zoom into area when clicking map_html = utils.js_helpers.zoom_on_click(map_html, area_map.get_name(), sectors_marker.get_name(), DEFAULT_AREA_ZOOM + 1) map_html = utils.js_helpers.enable_links_from_iframe(map_html) map_html = utils.js_helpers.replace_maps_placeholder(map_html) map_html = utils.js_helpers.replace_approx_placeholders_for_translations( map_html, APPROX_PLACEHOLDER) # Avoid zooming in when clicking on a sector area map_html = utils.js_helpers.remove_geojson_zoom_on_click(map_html) # replace the ids of all the html tags map_html = utils.js_helpers.replace_tag_ids(map_html, ['html'], generate_ids) return map_html if return_html else area_map
def profile(request, section=None, lat=None, lng=None, id=None, subsection=None): vegetation = get_object_or_404(Document, pk=983172) veg = None link = None if "next" in request.POST: return redirect("rehabilitation_design") if not lat: lat = request.COOKIES.get("lat") lng = request.COOKIES.get("lng") if lat and lng: link = f"/profile/{lat},{lng}/" try: lat = float(lat) lng = float(lng) center = geos.Point(lng, lat) veg = vegetation.spaces.get(geometry__intersects=center) veg = VegetationType.objects.get(spaces=veg) suburb = ReferenceSpace.objects.filter(source_id=334434, geometry__intersects=center) species = Species.objects.filter(vegetation_types=veg) if suburb: suburb = suburb[0].name.title() except: messages.error( request, f"We are unable to locate the relevant vegetation type.") suburb = None species = None context = { "lat": lat, "lng": lng, "link": link, "info": veg, "section": section, "subsection": subsection, "suburb": suburb, "page": Page.objects.get(slug="plant-selection"), "species": species, } if section == "plants": if subsection == "pioneers": context["title"] = "Pioneer species" species = species.filter(features__id=125) context["species_list"] = species elif subsection == "birds": context["title"] = "Bird-friendly species" context["sugarbird_list"] = species.filter( features__id__in=[111, 113, 114]) context["sunbird_list"] = species.filter(features__id=133) context["bird_list"] = species.filter(features__id=109) elif subsection == "insects": context["title"] = "Insect-friendly species" context["bee_list"] = species.filter(features__id=110) context["monkeybeetle_list"] = species.filter(features__id=112) elif subsection == "edible": context["title"] = "Edible plant species" species = species.filter(features__id=123) context["species_list"] = species elif subsection == "medicinal": context["title"] = "Medicinal plant species" species = species.filter(features__id=115) context["species_list"] = species context["photos_first"] = True elif section == "nearby": files = { "schools": 983409, "cemeteries": 983426, "parks": 983479, "rivers": 983382, "remnants": 983097, } capetown = get_object_or_404(ReferenceSpace, pk=988911) source_document = get_object_or_404(Document, pk=files[subsection]) center = geos.Point(x=lng, y=lat, srid=4326) center.transform(3857) # Transform Projection to Web Mercator radius = 1000 # Number of meters distance circle = center.buffer(radius) circle.transform(4326) # Transform back to WGS84 to create geojson layer = source_document.spaces.filter( Q(geometry__within=circle) | Q(geometry__intersects=circle)) if not layer: radius = 2000 # Number of meters distance circle = center.buffer(radius) circle.transform(4326) # Transform back to WGS84 to create geojson messages.warning( request, "We could not find anything in the regular area search, so we expanded our search to cover a wider area." ) layer = source_document.spaces.filter( Q(geometry__within=circle) | Q(geometry__intersects=circle)) map = folium.Map( location=[lat, lng], zoom_start=14, scrollWheelZoom=False, tiles=STREET_TILES, attr="Mapbox", ) folium.GeoJson( circle.geojson, name="geojson", ).add_to(map) Fullscreen().add_to(map) satmap = folium.Map( location=[lat, lng], zoom_start=17, scrollWheelZoom=False, tiles=SATELLITE_TILES, attr="Mapbox", ) def style_function(feature): return { "fillOpacity": 0, "weight": 4, "color": "#fff", } folium.GeoJson( circle.geojson, name="geojson", style_function=style_function, ).add_to(satmap) satmap.fit_bounds(map.get_bounds()) Fullscreen().add_to(satmap) folium.GeoJson( capetown.geometry.geojson, name="geojson", style_function=style_function, ).add_to(satmap) for each in layer: geom = each.geometry.intersection(circle) folium.GeoJson( geom.geojson, name="geojson", ).add_to(map) folium.GeoJson( geom.geojson, name="geojson", ).add_to(satmap) context["map"] = map._repr_html_() context["satmap"] = satmap._repr_html_() context["layer"] = layer context["source"] = source_document return render(request, "core/profile.html", context)
def space(request, id): info = get_object_or_404(ReferenceSpace, pk=id) geo = info.geometry if "download" in request.POST: response = HttpResponse(geo.geojson, content_type="application/json") response[ "Content-Disposition"] = f"attachment; filename=\"{info.name}.geojson\"" return response map = folium.Map( location=[info.geometry.centroid[1], info.geometry.centroid[0]], zoom_start=14, scrollWheelZoom=False, tiles=STREET_TILES, attr="Mapbox", ) folium.GeoJson( geo.geojson, name="geojson", ).add_to(map) if info.geometry.geom_type != "Point": # For a point we want to give some space around it, but polygons should be # an exact fit map.fit_bounds(map.get_bounds()) Fullscreen().add_to(map) satmap = folium.Map( location=[info.geometry.centroid[1], info.geometry.centroid[0]], zoom_start=17, scrollWheelZoom=False, tiles=SATELLITE_TILES, attr="Mapbox", ) folium.GeoJson( geo.geojson, name="geojson", ).add_to(satmap) if True: # For a point we want to give some space around it, but polygons should be # an exact fit, and we also want to show the outline of the polygon on the # satellite image satmap.fit_bounds(map.get_bounds()) def style_function(feature): return { "fillOpacity": 0, "weight": 4, } folium.GeoJson( info.geometry.geojson, name="geojson", style_function=style_function, ).add_to(satmap) Fullscreen().add_to(satmap) context = { "info": info, "map": map._repr_html_(), "satmap": satmap._repr_html_(), "center": info.geometry.centroid, } return render(request, "core/space.html", context)
mappa_gdf.plot(figsize=(12, 12)) # plt.show() import folium from folium import Map from folium.map import Layer, FeatureGroup, LayerControl, Marker from folium.plugins import MarkerCluster, FeatureGroupSubGroup, Fullscreen f_map = folium.Map(location=[44.75, 11], zoom_start=10, tiles='OpenStreetMap', control_scale=True, prefer_canvas=True) Fullscreen(title='Expand me', title_cancel='Exit fullscreen', force_separate_button=True).add_to(f_map) data = pd.read_csv('points1.csv') folium.Choropleth(geo_data='map2.geojson', data=data, columns=['NOME_COM', 'DANNO'], name='Damaged areas (epicenter)', fill_color='YlOrRd', legend_name='Damage entity', highlight=True, key_on='feature.properties.NOME_COM').add_to(f_map) # Function to change the marker color
fill_color='white', color='gray', fill_opacity=1).add_to(m) for i, point in enumerate( np.asarray(dispersed_zip_codes)[covered_associates_index]): folium.CircleMarker( point, radius=4, fill=True, # Set fill to True| fill_color='white', color='green', fill_opacity=1).add_to(m) Fullscreen(position='topleft', title='Full Screen', title_cancel='Exit Full Screen', force_separate_button=False).add_to(m) folium.LayerControl(collapsed=False).add_to(m) m.fit_bounds(m.get_bounds()) # Asociates clustering #m.save('src/views/routes_algorithm/maps/clustering_aguascalientes.html') max_distance = 1000 min_samples = 5 coords = not_covered_associates clusters, noise = get_clusters(coords, min_samples, max_distance, iterations=10)
# Add additional tile style options folium_map = dopemap.addTiles(folium_map, ['Stamen Toner', 'CartoDB dark_matter'], 14) # Add Circle Markers at designed locations # Clustering points dopemap.createMarkers( folium_map, df, 'lon', 'lat', 'GeoCardio data points', ['devenir_patient', 'lon', 'lat', 'geo_address', 'comment'], ['Devenir patient', 'Longitud', 'Latitud', 'Address', 'Comment'], 'devenir_patient', 20, colors) #Add legend to markers legend_html = dopemap.createLegend(folium_map, df['devenir_patient'], colors) # Add heatmap dopemap.createHeatmap(folium_map, df, 'lon', 'lat') # Add fullscreen option Fullscreen().add_to(folium_map) # Add layer control folium.LayerControl().add_to(folium_map) # Save map 1A ######################################################################################## output_file = str(output_folder / 'Devenir_patient.html') folium_map.save(output_file) # Add choropleth layer dopemap.createChoroplethMap(folium_map, gjs, 'Number of cases per ha', ['BFS_NUMMER', 'Rate_bussante_perha'], 'feature.properties.BFS_NUMMER', 'Number of cases per ha') # Save map 1B ######################################################################################## output_file = str(output_folder / 'Devenir_patient_choro.html') folium_map.save(output_file) ################ 2/ MAP
# -*- coding: utf-8 -*- import folium from folium.plugins import Fullscreen m = folium.Map(location=[41.9, -97.3], zoom_start=4) Fullscreen(position='topright', title='Expand me', titleCancel='Exit me', forceSeparateButton=True).add_to(m) m.save(outfile='fullscreen.html')
import folium from folium.plugins import Fullscreen m = folium.Map(location=[10, 0], zoom_start=2.1) Fullscreen().add_to(m) m.save(outfile='fullscreen.html') import geograpy url = 'http://www.bbc.com/news/world-europe-26919928' places = geograpy.get_place_context(url=url) folium.Marker([45.3288, -121.6625], popup='Mt. Hood Meadows').add_to(m)
def load_general_map(datafiles, generate_ids, return_html=True): """ Create a map that contains all the zones provided by the list of datafiles i.e. all areas combined in one map. This map only shows the markers that indicate an existing area. """ generate_ids.reset_seed() area_map = folium.Map(location=[-23.0390625, -18.299051014581817], zoom_start=2) area_map._id = generate_ids.next_id() # reassign id for child in area_map._children.values(): child._id = generate_ids.next_id() tile_layer = folium.TileLayer( tiles= 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', name='Satellite', attr= 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community' ) tile_layer._id = generate_ids.next_id() # reassign id tile_layer.add_to(area_map) # Add fullscreen button to map fs = Fullscreen() fs._id = generate_ids.next_id() fs.add_to(area_map) # layers = [] sectors_markers = [] placeholders = [] # Sectors layer zoomed_out_lyr = folium.FeatureGroup(name='Sector Markers') zoomed_out_lyr._id = generate_ids.next_id() # reassign id areas_cluster = MarkerCluster() areas_cluster._id = generate_ids.next_id() # reassign id for areadatafile in datafiles: area_data = {} with open(areadatafile, encoding='utf-8') as data: area_data = json.load(data) # sectors = area_data['sectors'] # # Create a Folium feature group for this layer, since we will be displaying multiple layers # sector_lyr = folium.FeatureGroup(name='sectors_layer') # for sector in sectors: # sector_map = folium.GeoJson( # os.path.dirname(os.path.abspath(areadatafile)) + # sector['sector_data'], # name=sector['name'], # tooltip=sector['name'], # style_function=lambda x: { # 'color': x['properties']['stroke'], # 'weight': x['properties']['stroke-width'], # 'opacity': SECTOR_OPACITY, # 'fillColor': x['properties']['stroke'], # } # ) # sector_html = helpers.generate_sector_html( # sector['name'], sector['link']) # sector_map.add_child(folium.Popup( # sector_html, max_width=POPUP_WIDTH, min_width=POPUP_WIDTH)) # sector_lyr.add_child(sector_map) # Parking # for parking in area_data['parkings']: # parking_marker = folium.Marker( # location=[parking['parking_latitude'], # parking['parking_longitude']], # popup=helpers.generate_parking_html([parking['parking_latitude'], # parking['parking_longitude']]), # tooltip='Parking', # icon=folium.Icon(color='red', icon='info-sign') # ) # sector_lyr.add_child(parking_marker) zoomed_out_icon = CustomIcon('static/images/marker/marker.png', icon_size=(MARKER_SIZE, MARKER_SIZE)) zoomed_out_icon._id = generate_ids.next_id() # reassign id html_redirect, _ = os.path.splitext( os.path.basename(os.path.normpath(areadatafile))) area_name = os.path.splitext(os.path.basename(areadatafile))[0] placeholder = area_name + PLACEHOLDER popup_html = folium.Html(utils.js_helpers.generate_area_popup_html( area_data['name'], area_name, html_redirect, placeholder), script=True) popup_html._id = generate_ids.next_id() # reassign id zone_popup = folium.Popup( popup_html, max_width=max(len(area_data['name']), len(BETA_VIDEOS_TEXT)) * 10) zone_popup._id = generate_ids.next_id() # reassign id placeholders.append(placeholder) sectors_marker = folium.Marker( location=[area_data['latitude'], area_data['longitude']], tooltip=area_data['name'], icon=zoomed_out_icon, popup=zone_popup, ) sectors_marker._id = generate_ids.next_id() # reassign id sectors_markers += [sectors_marker] # Group areas' markers when zoomed out areas_cluster.add_child(sectors_marker) zoomed_out_lyr.add_child(areas_cluster) area_map.add_child(zoomed_out_lyr) # area_map.add_child(sector_lyr) # layers += [(sector_lyr, zoomed_out_lyr)] layer_control = folium.LayerControl() layer_control._id = generate_ids.next_id() # reassign id layer_control.add_to(area_map) # Since folium does not support all the functionalities we need # we obtain them by injecting or editing JavaScript code in the map html map_html = area_map.get_root().render() # for sector_lyr, zoomed_out_lyr in layers: # # Hide or show layers depending on the zoom level # map_html = helpers.make_layer_that_hides( # map_html, area_map.get_name(), sector_lyr.get_name(), DEFAULT_AREA_ZOOM, False, False) # map_html = helpers.make_layer_that_hides( # map_html, area_map.get_name(), zoomed_out_lyr.get_name(), DEFAULT_AREA_ZOOM, True, True) # # Zoom into area when clicking # for marker in sectors_markers: # map_html = helpers.zoom_on_click( # map_html, area_map.get_name(), marker.get_name(), DEFAULT_AREA_ZOOM+1) map_html = utils.js_helpers.replace_custom_placeholders( map_html, placeholders) map_html = utils.js_helpers.replace_tag_ids(map_html, ['html'], generate_ids) return map_html if return_html else area_map