def __init__(self, **kwargs): # Default map center location and zoom level latlon = [40, -100] zoom = 4 # Interchangeable parameters between ipyleaflet and folium if 'center' in kwargs.keys(): kwargs['location'] = kwargs['center'] kwargs.pop('center') if 'location' in kwargs.keys(): latlon = kwargs['location'] else: kwargs['location'] = latlon if 'zoom' in kwargs.keys(): kwargs['zoom_start'] = kwargs['zoom'] kwargs.pop('zoom') if 'zoom_start' in kwargs.keys(): zoom = kwargs['zoom_start'] else: kwargs['zoom_start'] = zoom super().__init__(**kwargs) ee_basemaps['HYBRID'].add_to(self) folium.LatLngPopup().add_to(self) plugins.Fullscreen().add_to(self) self.fit_bounds([latlon, latlon], max_zoom=zoom)
def _add_map_controls(map_instance, minimap=True, mouse_position=True, measure_controll=True, draw=True): """Add aditional map controlls and features to the map\n map_instance: The map instance that was used to initialize the add_map() function\n minimap: Add minimap in the bottom left\n mouse_position: Coordinate information on hover\n measure_controll: adds a feature that allows the user to measure distance on the map\n draw: Adds the ability to draw different geometries on a map and save it as geojson \nexample:\n m = add_map(data= gdf)\n add_layer(data= gdf, color_column= 'color_values').add_to(m)\n add_map_controls(m) m.save('my_map.html') #Used when needing to plot large amounts of data which notebook can't handle """ map_instance = map_instance folium.TileLayer('OpenStreetMap').add_to(map_instance) folium.TileLayer('CartoDB dark_matter').add_to(map_instance) folium.TileLayer('CartoDB positron').add_to(map_instance) folium.LayerControl().add_to(map_instance) plugins.Fullscreen(position='topleft', title='Expand me', title_cancel='Exit me', force_separate_button=False).add_to(map_instance) if minimap: plugins.MiniMap(tile_layer='OpenStreetMap', position='bottomleft', toggle_display=True, minimized=False).add_to(map_instance) else: pass if mouse_position: fmtr = "function(num) {return L.Util.formatNum(num, 3) + ' º ';};" plugins.MousePosition(position='bottomleft', separator=' | ', prefix="Mouse:", lat_formatter=fmtr, lng_formatter=fmtr).add_to(map_instance) else: pass if measure_controll: plugins.MeasureControl(secondary_length_unit='kilometers', secondary_area_unit='sqkilometers', position='bottomright').add_to(map_instance) else: pass if draw: plugins.Draw(export=True).add_to(map_instance) else: pass return (map_instance)
def create_distribution_heatmap(name: str, lats: list, lons: list): """Create a folonium distribution heatmap. It plots a point for every couple of latitude and longitude given """ url_base = "http://server.arcgisonline.com/ArcGIS/rest/services/" service = "NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}" tileset = url_base + service heatmap_map = folium.Map( location=france_location, zoom_start=2, control_scale=True, tiles=tileset, attr="USGS style", ) data = [lon_lat for lon_lat in zip(lats, lons)] heatmap_map.add_child(plugins.HeatMap(data)) heatmap_map.add_child(plugins.MeasureControl()) heatmap_map.add_child( plugins.Fullscreen( position="topright", title="Expand me", title_cancel="Exit me", force_separate_button=True, ) ) heatmap_map.add_child(plugins.MeasureControl()) heatmap_map.add_child(plugins.MiniMap()) save_map(heatmap_map, name)
def index(request): if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = SearchForm() address = Search.objects.all().last() location = geocoder.osm(address) lat = location.lat lng = location.lng country = location.country if lat == None or lng == None: address.delete() return HttpResponse('You address input is invalid') # Create Map Object m = folium.Map(location=[19, -12], zoom_start=2) folium.Marker([lat, lng], tooltip='Click for more', popup=country).add_to(m) plugins.Fullscreen(position='topleft').add_to(m) # Get HTML Representation of Map Object m = m._repr_html_() context = { 'm': m, 'form': form, } return render(request, 'index.html', context)
def open_webb_and_save(mapka, fileHtml): folium.raster_layers.TileLayer('Open Street Map').add_to(mapka) folium.raster_layers.TileLayer('StamenTerrain').add_to(mapka) folium.raster_layers.TileLayer('CartoDB Positron').add_to(mapka) folium.raster_layers.TileLayer('StamenToner').add_to(mapka) folium.raster_layers.TileLayer('CartoDB Dark_Matter').add_to(mapka) folium.raster_layers.TileLayer('Stamen Watercolor').add_to(mapka) folium.LayerControl().add_to(mapka) minimap = plugins.MiniMap(toggle_display=True) mapka.add_child(minimap) plugins.Fullscreen(position='topright').add_to(mapka) measureControl = plugins.MeasureControl(position='topleft', active_color='red', completed_color='red', primary_length_unit='km') mapka.add_child(measureControl) draw = plugins.Draw(position='topleft', export='True') draw.add_to(mapka) html_page = f'{fileHtml}' mapka.save(fileHtml) mapka.save(html_page) new = 2 webbrowser.open(html_page, new=new) tkinter.messagebox.showinfo("Analiza gpx", "Zakończono analizę pliku i dołączono mapę")
def add_full_screen(m): """Adds a full-screen button in the top-left corner of the map. Unfortunately, the full-screen doesn't work in a Jupyter cell. Seems to work ok here: http://nbviewer.jupyter.org/github/python-visualization/folium/blob/master/examples/Plugins.ipynb""" from folium import plugins plugins.Fullscreen(position='topleft', title='Expand me', title_cancel='Exit me', force_separate_button=True).add_to(m)
def plot_cities(df, arg): """ Generalist function for creating interactive folium maps """ # Store the different messages and colours corresponding to the various data # which could be plotted dict_plot_cities = { 'consumption' : ["{}<br> Coal consumption: {} thousands tons",'#E37222'], 'production' : ["{}<br> Coal production: {} thousands tons",'#E8DC5C'], 'arriving_flux' : ["{}<br> Arriving coal: {} thousands tons",'#5CE8C2'], 'departing_flux' : ["{}<br> Departing coal: {} thousands tons",'#3893E8'] } # Initialize parameters color = '' df_ = df # Remove the cities whose net value is null df_ = df_[df_[arg]!=0] # Specify parameters of the folium map folium_map = folium.Map(location = sgs._location_map, zoom_start = sgs._zoom_map, tiles = "CartoDB dark_matter") # For each row in the data, add a cicle marker for index, row in df_.iterrows(): # Catch the popup message matching the data which is plotted popup = dict_plot_cities[arg][0] color = dict_plot_cities[arg][1] # Display the popup message popup = popup.format(row["city_name"],int(abs(row[arg])*sgs._ktons_per_unit)) # Define the radius of the circle so that its surface is proportional the the scalar radius = np.sqrt((abs(row[arg])))/np.pi # Add circle marker to the map folium.CircleMarker(location = (row["latitude"],row["longitude"]), radius = radius, color = color, popup = popup, fill = True).add_to(folium_map) # Enable folium measure tool measure_control = plugins.MeasureControl(primary_length_unit='kilometers', primary_area_unit='sqkilometers') # Enable folium fullscreen plugin fullscreen = plugins.Fullscreen() # Add plugins to the map measure_control.add_to(folium_map) fullscreen.add_to(folium_map) return folium_map
def test_fullscreen(): m = folium.Map([47, 3], zoom_start=1) fs = plugins.Fullscreen() m.add_child(fs) m._repr_html_() out = m._parent.render() # verify that the fullscreen control was rendered assert 'L.control.fullscreen().addTo' in out
def runmodel(input_date): date = (pd.to_datetime(input_date)).date() modelfilename = 'data/lin_model.sav' scalerfilename = 'data/lin_scaler.sav' lin = pickle.load(open(modelfilename, 'rb')) scaler = pickle.load(open(scalerfilename, 'rb')) testX = build_input(date) testx = testX[['TL1', 'Tmin', 'Tmax', 'd_lm', 'sqrt_dw', 'sqrt_dp']] X = scaler.transform(testx) Y = lin.predict(X) l = len(Y) for i in range(l): if Y[i] < 0: Y[i] = 0 smallY = Y.reshape(101, 101) # y5 = ndimage.zoom(smallY, 5) NN = np.genfromtxt("data/nans100.csv", delimiter=',').transpose() TT = np.multiply(smallY, NN) xx = np.linspace(min(testX['lon']), max(testX['lon']), 101) yy = np.linspace(min(testX['lat']), max(testX['lat']), 101) colors = ['darkgreen', 'green', 'yellow', 'orange', 'red', 'darkred'] vmin = 0 vmax = 50 levels = len(colors) cfig = plt.contourf(xx, yy, TT, levels, alpha=1.0, colors=colors, linestyles='None', vmin=vmin, vmax=vmax) geojson = geojsoncontour.contourf_to_geojson(contourf=cfig, min_angle_deg=0.0, ndigits=5, stroke_width=0.5, fill_opacity=1.0) geomap = folium.Map(location=[41.89, -87.64], zoom_start=13, tiles="stamenterrain") folium.GeoJson(geojson, style_function=lambda x: { 'color': x['properties']['stroke'], 'weight': x['properties']['stroke-width'], 'fillColor': x['properties']['fill'], 'fillOpacity': 0.65 }).add_to(geomap) plugins.Fullscreen(position='topright', force_separate_button=True).add_to(geomap) fname = 'static/' + str(dt.datetime.now()) + '.html' geomap.save(f'flaskapp/' + fname) return fname
def setControlVisibility(self, layerControl=True, fullscreenControl=True, latLngPopup=True): if layerControl: folium.LayerControl().add_to(self) if fullscreenControl: plugins.Fullscreen().add_to(self) if latLngPopup: folium.LatLngPopup().add_to(self)
def setup_map(center, zoom_start=14, filename="draw.geojson"): """Create a basic folium map object""" map_ = folium.Map( location=center, zoom_start=zoom_start, tiles="cartodbdark_matter", ) plugins.Fullscreen(position="topleft").add_to(map_) plugins.Draw(filename=filename, export=True, position="topleft").add_to(map_) return map_
def express(): form = ExpressForm() start_coords = (16.79631, 96.16469) map_tem = folium.Map(location=start_coords, zoom_start=14) plugins.Fullscreen().add_to(map_tem) for k in basemaps: basemaps[k].add_to(map_tem) folium.LayerControl().add_to(map_tem) el = folium.MacroElement().add_to(map_tem) el._template = elements["set_express_locations"] map_tem.save(os.path.join(os.getcwd(), "app", "static", "map.html")) return render_template('express.html', form=form)
def plot_cities_transiting_flux(df): """ Function specialized in the creation of interactive maps representing goods transit """ # Initialize parameters color = '' arg = 'transiting_flux' df_ = df # Remove the cities whose net transiting flux is null df_ = df_[df_[arg]!=0] # Specify parameters of the folium map folium_map = folium.Map(location = sgs._location_map, zoom_start = sgs._zoom_map, tiles = "CartoDB dark_matter") # For each row in the data, add a cicle marker for index, row in df_.iterrows(): # Generate a popup message that is shown on click and display it popup = "{}<br> Arriving coal: {} thousands tons<br>" popup += "Departing coal: {} thousands tons<br> Total coal transit: {} thousands tons" popup = popup.format(row["city_name"], int(abs(row['arriving_flux'])*sgs._ktons_per_unit), int(abs(row['departing_flux'])*sgs._ktons_per_unit), int(abs(row['transiting_flux'])*sgs._ktons_per_unit)) # Set colour to violet color = '#A85CE8' # violet # Define the radius of the circle so that its surface is proportional the the # scalar (transit) radius = np.sqrt((abs(row[arg])))/np.pi # Add circle marker to the map folium.CircleMarker(location = (row["latitude"],row["longitude"]), radius = radius, color = color, popup = popup, fill = True).add_to(folium_map) # Enable folium measure tool measure_control = plugins.MeasureControl(primary_length_unit='kilometers', primary_area_unit='sqkilometers') # Enable folium fullscreen plugin fullscreen = plugins.Fullscreen() # Add plugins to the map measure_control.add_to(folium_map) fullscreen.add_to(folium_map) return folium_map
def generate_base_map(radius, location=[50.0, 8.0], tiles="OpenStreetMap"): zoom_start = get_zoom_level(radius) new_map = folium.Map(location=location, control_scale=True, zoom_start=zoom_start, tiles=tiles) # Fullscreen mode plugins.Fullscreen(position='topright', force_separate_button=True).add_to(new_map) folium.TileLayer('openstreetmap').add_to(new_map) folium.TileLayer('Stamen Terrain').add_to(new_map) return new_map
def create_map(): ''' Function for creating a map :return: None ''' points = points_feat.create_points(flask_path) # points = points_feat.create_points(main_path) FEATURES = points['features'] print(FEATURES) points_COORDINATES = points['coordinates'] DEF_TIME = points['set-time'] folium_map = folium.Map(location=[40.738, -73.98], zoom_start=12, tiles="CartoDB dark_matter") # MiniMap plugin minimap = plugins.MiniMap() folium_map.add_child(minimap) # Fullscreen plugin plugins.Fullscreen(position='topright', title='Expand me', title_cancel='Exit me', force_separate_button=True).add_to(folium_map) # Timestamp plugin plugins.TimestampedGeoJson( { 'type': 'FeatureCollection', 'features': FEATURES }, period='PT4H', add_last_point=True).add_to(folium_map) COORDINATES = [] for c in points_COORDINATES: newlst = [c[1], c[0]] aqi = pollution.get_air_data(newlst, DEF_TIME)[0] / 2.5 newlst.append(aqi) COORDINATES.append(newlst) print(COORDINATES) heat_map = plugins.HeatMap(COORDINATES, radius=50) heat_map.layer_name = 'Air Quality' folium_map.add_child(heat_map) folium_map.add_child(folium.LayerControl()) print('> Done.') folium_map.save("../NY_MAP/templates/my_map.html")
def gerar_mapa(request): ip = get('https://api.ipify.org').text response1 = DbIpCity.get(ip, api_key='free') #print(response1) m = folium.Map([response1.latitude, response1.longitude], tiles='cartodbpositron', zoom_start=5, prefer_canvas=True) # Minimapa minimap = plugins.MiniMap(toggle_display=True) m.add_child(minimap) # add full screen button to map plugins.Fullscreen(position='topright').add_to(m) # Declaring points of latitude and longitude #my_locations = [(response1.latitude, response1.longitude),(-25.45,-49.34),(-25.45,-49.34)] doc_ref = db.collection('Pegasus').document(u'Exame') docs = doc_ref.get() exp = docs.to_dict() print(exp['Geopoints'][0]) print(exp['Geopoints'][1]) my_locations = [(exp['Geopoints'][0], exp['Geopoints'][1])] marker_cluster = MarkerCluster(my_locations) marker_cluster.add_to(m) #HeatMap(df).add_to(m) m.save('lab/templates/lab/mapa.html') table_file = open('lab/templates/lab/mapa.html') map_lines = table_file.readlines() table_file.close() table_file = open('lab/templates/lab/mapa.html', 'w+') first_lines = [ "{% extends 'lab/base.html'%} \n", #"{% load static %} \n", "{% block content %} \n", "{% if user.is_authenticated %} \n" ] end_lines = ["\n{% endif %}\n", "{% endblock %}"] table_file.writelines(first_lines) table_file.writelines(map_lines) table_file.close() table_file = open('lab/templates/lab/mapa.html', 'a+') table_file.writelines(end_lines) table_file.close() return render(request, 'lab/mapa.html')
def inventory_map_only(invent): """ Create map with inventory only :param invent: GeoDataFrame, Dataframe containing all inventory. :return: """ # Initialize Map inventory_map = folium.Map([43, 0], zoom_start=4, tiles=None) folium.TileLayer("CartoDB dark_matter", name="Dark mode").add_to(inventory_map) folium.TileLayer("OpenStreetMap", name="Open Street Map").add_to(inventory_map) d = {} invent_types = invent['CO2/CO2e emissions source'].unique() for cl in invent_types: d["{0}".format(cl)] = folium.FeatureGroup( name=cl).add_to(inventory_map) for index, row in invent.iterrows(): radius = 1 color = "#368534" # green tooltip = "[" + str(round(row['latitude'], 2)) + " ; " + str( round(row['longitude'], 2)) + "]" pop = str(round(row['CO2/CO2e emissions (in tonnes per year)'], 0)) title = "" + str( round(row['CO2/CO2e emissions (in tonnes per year)'], 0)) + " T/y " + row['CO2 or CO2e'] popup_html = """<h4>""" + title + """</h4><p>""" + tooltip + """</p>""" + """<p>""" + str( row['CO2/CO2e emissions source']) + ", from " + str( row['Data source']) + """</p>""" popup = folium.Popup(popup_html, max_width=450) d[row['CO2/CO2e emissions source']].add_child( folium.CircleMarker(location=(row["latitude"], row["longitude"]), radius=radius, color=color, popup=popup, tooltip=str(row['CO2/CO2e emissions source']), fill=True)) folium.map.LayerControl(collapsed=False).add_to(inventory_map) plugins.Fullscreen(position='topright', title='Expand me', title_cancel='Exit me', force_separate_button=True).add_to(inventory_map) #inventory_map.save("inventory_map.html") return inventory_map
def plot_cities_production(df): """ Function specialized in the creation of interactive maps representing production centers """ # Initialize parameters arg = 'production' df_ = df # Remove the cities whose net production is null df_ = df_[df_[arg]!=0] # Specify parameters of the folium map folium_map = folium.Map(location = sgs._location_map, zoom_start = sgs._zoom_map, tiles = "CartoDB dark_matter") # For each row in the data, add a cicle marker for index, row in df_.iterrows(): # Generate a popup message that is shown on click. popup = "{}<br> {}<br>Coal production: {} thousands tons" # Set the colour to the one which is specified in the settings folder color = sgs._production_colors[int(row['type_production'])-1] # Display the popup message popup = popup.format(row["city_name"],sgs._descr[int(row['type_production'])-1], int(abs(row[arg])*sgs._ktons_per_unit)) # Define the radius of the circle so that its surface is proportional the the scalar (production) radius = np.sqrt((abs(row[arg])))/np.pi # Add circle marker to the map folium.CircleMarker(location = (row["latitude"],row["longitude"]), radius = radius, color = color, popup = popup, fill = True).add_to(folium_map) # Enable folium measure tool measure_control = plugins.MeasureControl(primary_length_unit='kilometers', primary_area_unit='sqkilometers') # Enable folium fullscreen plugin fullscreen = plugins.Fullscreen() # Add plugins to the map measure_control.add_to(folium_map) fullscreen.add_to(folium_map) return folium_map
def test_fullscreen(): m = folium.Map([47, 3], zoom_start=1) fs = plugins.Fullscreen().add_to(m) out = normalize(m._parent.render()) # verify that the fullscreen control was rendered tmpl = Template(""" L.control.fullscreen( {{ this.options|tojson }} ).addTo({{this._parent.get_name()}}); """) assert normalize(tmpl.render(this=fs)) in out
def set_control_visibility( self, layerControl=True, fullscreenControl=True, latLngPopup=True ): """Sets the visibility of the controls on the map. Args: layerControl (bool, optional): Whether to show the control that allows the user to toggle layers on/off. Defaults to True. fullscreenControl (bool, optional): Whether to show the control that allows the user to make the map full-screen. Defaults to True. latLngPopup (bool, optional): Whether to show the control that pops up the Lat/lon when the user clicks on the map. Defaults to True. """ if layerControl: folium.LayerControl().add_to(self) if fullscreenControl: plugins.Fullscreen().add_to(self) if latLngPopup: folium.LatLngPopup().add_to(self)
def interactive_facilities_map(facilities_nm): facilities = gpd.read_file(facilities_nm) facilities = add_facilities_icon(facilities) map_center = get_map_center(facilities) maploc = folium.Map(location=map_center, zoom_start=6, prefer_canvas=True, tiles="Stamen Terrain") marker_cluster = MarkerCluster().add_to(maploc) facility_locations = facilities[['FacilityLatitude', 'FacilityLongitude']] fclty_pnts = facility_locations.values.tolist() for fc_pnt in range(0, len(fclty_pnts)): f = folium.Figure() # add campsite mini map into popup window (due to high load times, this feature was removed) # facility_id = facilities['FacilityID'][fc_pnt] # campsite_map = interactive_campsite_map(campsite_nm, facility_id) # campsite_map.add_to(f) facility_popup_info = f"___________________________________________________________________________________________ <br> \ <b style='color:Tomato;'>Facility Name:</b> {facilities['FacilityName'][fc_pnt]} <br><br> \ <b style='color:Tomato;'>Facility ID:</b> {facilities['FacilityID'][fc_pnt]} <br><br> \ <b style='color:Tomato;'>Facility Type:</b> {facilities['FacilityTypeDescription'][fc_pnt]} <br><br> \ <b style='color:Tomato;'> Total Campsites:</b> {facilities['TotalCampsites'][fc_pnt]} <br><br> \ <b style='color:Tomato;'>Reservable:</b> {facilities['Reservable'][fc_pnt]} <br><br> \ {facilities['FacilityDescription'][fc_pnt]} <br><br>\ ___________________________________________________________________________________________ <br>" iframe = folium.IFrame(html=facility_popup_info, width=500, height=300) f.add_to(iframe) popup = folium.Popup(iframe, max_width=2650) facility_icon = folium.Icon(color = 'green')#icon= facilities['FacilityTypeIcon'][fc_pnt], icon='map-pin', prefix='fa') folium.Marker(fclty_pnts[fc_pnt], popup= popup, icon = facility_icon, tooltip=facilities['FacilityName'][fc_pnt]).add_to(marker_cluster) plugins.Fullscreen( position="topright", title="Expand me", title_cancel="Exit me", force_separate_button=True, ).add_to(maploc) minimap = plugins.MiniMap() maploc.add_child(minimap) plugins.Geocoder().add_to(maploc) maploc.save("../docs/facility_map.html") return maploc
def GENERATE_MAP_MAIN_FUNCTION(path='./data/combined_data.tsv'): start=dt.now() bike_point_list=[] longitude_list=[] latitude_list=[] print('Generating map...') count=0 with open(path) as tsvfile: reader = csv.reader(tsvfile, delimiter='\t') for row in reader: if count !=0: if not row[0] in bike_point_list: bike_point_list.append(row[0]) longitude_list.append(float(row[1])) latitude_list.append(float(row[2])) count+=1 # Make a data frame with dots to show on the map data = pd.DataFrame({ 'lat':latitude_list, 'lon':longitude_list, 'name':bike_point_list }) # Make an empty map m = folium.Map(location=[st.mean(longitude_list), st.mean(latitude_list)], tiles="OpenStreetMap", zoom_start=11.5,control_scale=True) plugins.Fullscreen( position='topright', title='Expand me', title_cancel='Exit me', force_separate_button=True ).add_to(m) #Including some plugins to map #plugins.HeatMap(defining_heat_map_list()).add_to(m) plugins.LocateControl().add_to(m) # I can add marker one by one on the map for i in range(0,len(data)): folium.Marker([data.iloc[i]['lon'], data.iloc[i]['lat']], popup=data.iloc[i]['name'],icon=folium.Icon(color='red', icon='info-sign')).add_to(m) # Save it as html m.save('./map/bike_Brussels-points-map.html') print('The bike_Brussels-points-map.html file was already generated') print(dt.now()-start)
def get_map(search_key): lat = df.loc[df['address'] == search_key, 'latitude'].iloc[0] lon = df.loc[df['address'] == search_key, 'longitude'].iloc[0] f = folium.Figure(height=600) m = folium.Map(location=[lat, lon], tiles="cartodbpositron", zoom_start=17).add_to(f) icon_path = r"./static/icons/billboard_icon.png" icon_png = folium.features.CustomIcon(icon_image=icon_path, icon_size=(50, 50)) folium.Marker( [lat, lon], icon=icon_png, tooltip=search_key + " Billboard", ).add_to(m) plugins.Fullscreen().add_to(m) map_html = m._repr_html_() return map_html
def make_map_and_marker(self): self.fileGPX = self.pathLbl["text"] self.fileHTML = self.htmlEnt.get() story = self self.storyTxt.delete(0.0, END) self.storyTxt.insert(0.0, story) pointsXY = self.points_xy() lat = float(sum(p[0] for p in pointsXY) / len(pointsXY)) lon = float(sum(p[1] for p in pointsXY) / len(pointsXY)) mapka = folium.Map(location=[lat, lon], zoom_start=13, control_scale=True) folium.PolyLine(pointsXY, color="blue", weight=3.5, opacity=1).add_to(mapka) folium.CircleMarker(location=[lat, lon], color='none', radius=25, fill_color='blue', popup=self, tooltip=self.fileGPX).add_to(mapka) folium.raster_layers.TileLayer('Open Street Map').add_to(mapka) folium.raster_layers.TileLayer('StamenTerrain').add_to(mapka) folium.raster_layers.TileLayer('CartoDB Positron').add_to(mapka) folium.raster_layers.TileLayer('StamenToner').add_to(mapka) folium.raster_layers.TileLayer('CartoDB Dark_Matter').add_to(mapka) folium.raster_layers.TileLayer('Stamen Watercolor').add_to(mapka) folium.LayerControl().add_to(mapka) minimap = plugins.MiniMap(toggle_display=True) mapka.add_child(minimap) plugins.Fullscreen(position='topright').add_to(mapka) measureControl = plugins.MeasureControl(position='topleft', active_color='red', completed_color='red', primary_length_unit='km') mapka.add_child(measureControl) draw = plugins.Draw(position='topleft', export='True') draw.add_to(mapka) mapka.save(self.fileHTML) html_page = f'{self.fileHTML}' mapka.save(html_page) new = 2 webbrowser.open(html_page, new=new) tkinter.messagebox.showinfo( "Analiza gpx", "Zakończono analizę pliku i dołączono mapę")
def get_coordinates(keyword): objid = df.loc[df["WARD_NAME"] == str(keyword), "OBJECTID"].iloc[0] for i in range(len(geojsonData["features"])): if (geojsonData["features"][i]["properties"]["OBJECTID"] == objid): area_co = geojsonData["features"][i] strt_co = geojsonData["features"][i]["geometry"]["coordinates"][0][ 0][0] f = folium.Figure(height=350) m = folium.Map( location=[strt_co[1], strt_co[0]], tiles="cartodbpositron", zoom_start=13, ).add_to(f) folium.GeoJson(area_co, name='geojson', tooltip="<b>{}</b>".format(keyword)).add_to(m) plugins.Fullscreen().add_to(m) map_html = m._repr_html_() return map_html
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 displayImage(image, minVal, maxVal, mapBounds): center_long = mapBounds.getInfo()['coordinates'][0][0][0] center_lat = mapBounds.getInfo()['coordinates'][0][0][1] my_map = folium.Map(location=[center_lat, center_long], zoom_start=8, height=700) vis_params = {'min': minVal, 'max': maxVal} my_map.add_ee_layer(image, vis_params, 'Image') # add a layer control panel to the map my_map.add_child(folium.LayerControl()) # add fullscreen button plugins.Fullscreen().add_to(my_map) # display the map. display(my_map) return
def create_folium_map(location=[0, 0], zoom_start=2, max_zoom=13): tiles_str = 'https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png?access_token=' token_str = 'pk.eyJ1IjoiZ3RzYXBlbGFzIiwiYSI6ImNqOWgwdGR4NTBrMmwycXMydG4wNmJ5cmMifQ.laN_ZaDUkn3ktC7VD0FUqQ' attr_str = 'Map data ©<a href="http://openstreetmap.org">OpenStreetMap</a>contributors, ' \ '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' \ 'Imagery \u00A9 <a href="http://mapbox.com">Mapbox</a>' m = folium.Map(location=location, zoom_start=zoom_start, max_zoom=max_zoom, tiles=tiles_str + token_str, attr=attr_str, control_scale=True) # folium.TileLayer('openstreetmap').add_to(m) plugins.Fullscreen(position='topright', title='Expand', title_cancel='Exit', force_separate_button=True).add_to(m) return m
def test_fullscreen(): m = folium.Map([47, 3], zoom_start=1) fs = plugins.Fullscreen() m.add_child(fs) m._repr_html_() out = m._parent.render() # verify that the fullscreen control was rendered tmpl = Template(""" L.control.fullscreen({ position: '{{this.position}}', title: '{{this.title}}', titleCancel: '{{this.titleCancel}}', forceSeparateButton: {{this.forceSeparateButton}}, }).addTo({{this._parent.get_name()}}); {{this._parent.get_name()}}.on('enterFullscreen', function(){ console.log('entered fullscreen'); }); """) assert ''.join(tmpl.render(this=fs).split()) in ''.join(out.split())
def index(request): m = folium.Map(location=[19, 12], zoom_start=2) map1 = raster_layers.TileLayer(tiles='CartoDB Dark_Matter').add_to(m) map2 = raster_layers.TileLayer(tiles='CartoDB Positron').add_to(m) map3 = raster_layers.TileLayer(tiles='Stamen Terrain').add_to(m) map4 = raster_layers.TileLayer(tiles='Stamen Toner').add_to(m) map5 = raster_layers.TileLayer(tiles='Stamen Watercolor').add_to(m) folium.LayerControl().add_to(m) qs = Data.objects.all() df = read_frame(qs, fieldnames=['country', 'latitude', 'longitude', 'population']) # print(df) for (index, rows) in df.iterrows(): folium.Marker(location=[rows.loc['latitude'], rows.loc['longitude']], popup=rows.loc['population']).add_to(m) plugins.Fullscreen().add_to(m) m = m._repr_html_() context = { 'm': m } return render(request, 'dashboard/index.html', context)