def make_empty_map(lat_center=51.326863, lon_center=10.354922, zoom=5): fig = [ dl.Map( [ dl.TileLayer(url=mapURL, attribution=attribution, tileSize=512, zoomOffset=-1), dl.LayerGroup(id="layer"), dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?", layers="dwd:RX-Produkt", format="image/png", transparent=True, opacity=0.7, version='1.3.0', detectRetina=True), dl.LocateControl( options={'locateOptions': { 'enableHighAccuracy': True }}), ], center=[lat_center, lon_center], zoom=zoom, style={ 'width': '100%', 'height': '45vh', 'margin': "auto", "display": "block" }, id='map') ] return fig
def render_example6(): # Generate some in-memory data. bermuda = dlx.dicts_to_geojson([dict(lat=32.299507, lon=-64.790337)]) biosfera = dlx.geojson_to_geobuf( dlx.dicts_to_geojson([dict(lat=29.015, lon=-118.271)])) with open("data/KCNeighborhood.json", 'r') as f: statesData = json.load(f) return [ dl.Map( center=[39, -98], zoom=4, children=[ dl.TileLayer(), dl.GeoJSON(data=bermuda), # in-memory geojson (slowest option) dl.GeoJSON( data=biosfera, format="geobuf" ), # in-memory geobuf (smaller payload than geojson) dl.GeoJSON( data=statesData, id="capitals"), # geojson resource (faster than in-memory) ], style={ 'width': '100%', 'height': '50vh', 'margin': "auto", "display": "block" }, id="map"), html.Div(id="state"), html.Div(id="capital") ]
def update_output(value): mapUpdate = [] setDate(value) ctg = [ "{}+".format(mark, marks[i + 1]) for i, mark in enumerate(marks[:-1]) ] + ["{}+".format(marks[-1])] colorbar = dlx.categorical_colorbar( categories=["0+", "5+", "10+", "15+", "20+", "25+", "30+", "35+"], colorscale=colorscale, width=300, height=30, position="bottomleft") options = dict(hoverStyle=dict(weight=5, color='#666', dashArray=''), zoomToBoundsOnClick=True) geojson = dlx.geojson(data, id="geojson", defaultOptions=options, style=get_style2) info = html.Div(children=get_info(), id="info", className="info", style={ "position": "absolute", "top": "10px", "right": "10px", "z-index": "1000", "background": "white" }) mapUpdate = [dl.TileLayer(), geojson, colorbar, info] return mapUpdate
def get_map(run_by, paved_status, lighted_status, spaces_range): df = lots[(lots["operator"].isin(run_by)) & (lots["is_paved"].isin(paved_status)) & (lots["light"].isin(lighted_status)) & (lots["available_spaces"] >= spaces_range[0]) & (lots["available_spaces"] <= spaces_range[1])] titles = df[df.columns[0]] lat = df[df.columns[7]] long = df[df.columns[8]] avg_lat = sum(lat) / len(lat) avg_long = sum(long) / len(long) print(len(df)) points = [] for i in range(0, len(lat) - 1): points.append(dict(lat=lat[i], lon=long[i])) return dl.Map(center=[avg_lat, avg_long], zoom=7, children=[ dl.TileLayer(), dl.GeoJSON(data=dlx.dicts_to_geojson(points)) ], style={ 'width': '100%', 'height': '50vh', 'margin': "auto", "display": "block" }, id="map-object")
def create_map(self): self.ns = Namespace("dlx", "scatter") self.markers = [ dl.Marker( dl.Tooltip(f"({pos[0]}, {pos[1]}), time:{self.times[i]}"), position=pos, id="marker{}".format(i)) for i, pos in enumerate(self.locations) ] self.cluster = dl.MarkerClusterGroup( id="markers", children=self.markers, options={"polygonOptions": { "color": "red" }}) self.app = dash.Dash(external_scripts=[ "https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js" ]) self.polyline = dl.Polyline(positions=self.locations) self.app.layout = html.Div([ dl.Map([ dl.TileLayer(), self.cluster, self.polyline, dl.LayerGroup(id="layer") ], id="map", center=(40.4259, -86.9081), zoom=8, style={'height': '100vh'}), ])
def render_example5(): # Example from https://plot.ly/python/scatter-plots-on-maps/#us-airports-map color_domain = dict(domainMin=20, domainMax=40, colorscale=['white', 'orange', 'red']) return [ html.H1("Example 5: GeoTIFFOverlay"), html.P("US airports (most arrivals)"), dl.Map( style={ 'width': '1000px', 'height': '500px' }, center=[25, 45], zoom=5, children=[ dl.TileLayer( url= "https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_nolabels/{z}/{x}/{y}.png" ), dl.GeoTIFFOverlay(id=GEOTIFF_ID, interactive=True, url="/assets/tz850.tiff", band=1, opacity=0.9, **color_domain), dl.Colorbar(width=200, height=20, **color_domain, unit="°C", style={'color': 'white'}), html.Div(id=GEOTIFF_MARKER_ID) ]), ]
def update_radio(input_value): if input_value != None: print("update_radio", input_value) def get_style(feature): color = [ colorscale[i] for i, item in enumerate(marks) if feature["properties"][input_value] > item ][-1] return dict(fillColor=color, weight=2, opacity=1, color='white', dashArray='3', fillOpacity=0.7) options = dict(hoverStyle=dict(weight=5, color='#666', dashArray=''), zoomToBoundsOnClick=True) geojson = dlx.geojson(data, id="geojson", defaultOptions=options, style=get_style) return html.Div([ dl.Map(children=[dl.TileLayer(), geojson], center=[51.51, -0.083], zoom=11) ], style={ 'width': '150%', 'height': '75vh' }, id="map")
def update_map(rows, viewData): dff = pd.DataFrame.from_dict(viewData) # get the lat and lon of the selected row lat = dff.iat[rows[0], 13] lon = dff.iat[rows[0], 14] return [ dl.Map( style={ 'width': '1000px', 'height': '500px' }, center=[30.75, -97.48], zoom=10, children=[ dl.TileLayer(id="base-layer-id"), # Marker with tool tip and popup dl.Marker(position=[lat, lon], children=[ dl.Tooltip(dff.iat[rows[0], 4]), dl.Popup([ html.H1("Animal Name"), html.P(dff.iat[rows[0], 9]) ]) ]) ]) ]
def render_example5(): color_domain = dict(domainMin=20, domainMax=40, colorscale=['white', 'orange', 'red']) return [ html.H1("Example 5: GeoTIFFOverlay"), html.P("Middle East Temperatures"), dl.Map( style={ 'width': '1000px', 'height': '500px' }, center=[25, 45], zoom=5, children=[ dl.TileLayer( url= "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_nolabels/{z}/{x}/{y}.png" ), dl.GeoTIFFOverlay(id=GEOTIFF_ID, interactive=True, url="/assets/tz850.tiff", band=1, opacity=0.8, **color_domain), dl.Colorbar(width=200, height=20, **color_domain, unit="°C", style={'color': 'black'}), html.Div(id=GEOTIFF_MARKER_ID) ]), ]
def build_alerts_map(): """ The following function mobilises functions defined hereabove or in the utils module to instantiate and return a dl.Map object, corresponding to the "Alerts and Infrastructure" view. """ map_object = dl.Map( center=[44.73, 4.27], # Determines the point around which the map is centered zoom=9, # Determines the initial level of zoom around the center point children=[ dl.TileLayer(id='tile_layer'), build_departments_geojson(), build_filters_object(map_type='alerts'), build_legend_box(map_type='alerts'), dl.MarkerClusterGroup( children=build_sites_markers(sites_with_live_alerts=[]), id='sites_markers'), dl.LayerGroup(id='vision_polygons'), html.Div(id="live_alerts_marker"), html.Div(id="live_alert_header_btn"), html.Div(id='fire_markers_alerts') ], # Will contain the past fire markers of the alerts map style=map_style, # Reminder: map_style is imported from utils.py id='map') return map_object
def get_base_toner_tile_layer(): # Base tile layer url = "http://{s}.tile.stamen.com/toner-background/{z}/{x}/{y}.png" attribution = ( 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, ' 'under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. ' 'Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.' ) base_tile_layer = dl.TileLayer(url=url, attribution=attribution) return base_tile_layer
def update_map(value): children = [dl.TileLayer()] geojson_states = build_geojson_states() children.append(geojson_states) if value: classes = PROPERTIES[value]['classes'] color_scale = PROPERTIES[value]['color_scale'] color_bar = build_color_bar(classes, color_scale) children.append(color_bar) geojson_counties = build_geojson_counties(color_prop=value) else: geojson_counties = build_geojson_counties() children.append(geojson_counties) return [children]
def generate_map_plot(data): if data is not None: start_point = data['STATION_NAME'].item() point = [data['LAT'].item(), data['LON'].item()] fig = [ dl.Map( [ dl.TileLayer(url=mapURL, attribution=attribution, tileSize=512, zoomOffset=-1), dl.LayerGroup(id="layer"), dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?", layers="dwd:SAT_WELT_KOMPOSIT", format="image/png", transparent=True, opacity=0.7, version='1.3.0', detectRetina=True), dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?", layers="dwd:SAT_EU_RGB", format="image/png", transparent=True, opacity=0.7, version='1.3.0', detectRetina=True), dl.LocateControl(options={ 'locateOptions': { 'enableHighAccuracy': True } }), dl.Marker(position=point, children=dl.Tooltip(start_point)), ], center=point, zoom=4, style={ 'width': '100%', 'height': '35vh', 'margin': "auto", "display": "block" }, id='map') ] else: # make an empty map fig = make_empty_map() return fig
def get_component(eq_data): """Return the map component with earthquakes represented as circles. Keyword arguments: eq_data -- EarthquakeData object containing the quakes to be drawn. """ return dl.Map(id='quake-map', center=[33.7, -117.3], zoom=8, children=[ dl.TileLayer(url=api_url, attribution=attribution), html.Div(id='test-id', children=[get_event_layer(eq_data)]) ])
def render_example3(): return [ html.H1("Example 3: ImageOverlay"), dl.Map(style={ 'width': '1000px', 'height': '500px' }, bounds=[[40.712216, -74.22655], [40.773941, -74.12544]], children=[ dl.TileLayer(), dl.ImageOverlay(opacity=0.5, url="/assets/newark_nj_1922.jpg", bounds=[[40.712216, -74.22655], [40.773941, -74.12544]]) ]), ]
def generate_map_plot(df): if df is not None: lons = df.lons.values lats = df.lats.values trajectory = np.vstack([lats, lons]).T.tolist() start_point = df.source.values[0] end_point = df.destination.values[0] zoom, center = zoom_center(lons, lats, width_to_height=8) fig = [ dl.Map( [ dl.TileLayer(url=mapURL, attribution=attribution, tileSize=512, zoomOffset=-1), dl.LayerGroup(id="layer"), dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?", layers="dwd:RX-Produkt", format="image/png", transparent=True, opacity=0.7), dl.LocateControl(options={ 'locateOptions': { 'enableHighAccuracy': True } }), dl.Polyline(positions=trajectory), dl.Marker(position=trajectory[0], children=dl.Tooltip(start_point)), dl.Marker(position=trajectory[-1], children=dl.Tooltip(end_point)) ], center=[center['lat'], center['lon']], zoom=zoom, style={ 'width': '100%', 'height': '45vh', 'margin': "auto", "display": "block" }, id='map') ] else: # make an empty map fig = make_empty_map() return fig
def render_example4(): return [ html.H1("Example 4: VideoOverlay"), dl.Map(style={ 'width': '1000px', 'height': '500px' }, bounds=[[32, -130], [13, -100]], children=[ dl.TileLayer(url=mapbox_url.format( id="satellite-streets-v9", access_token=mapbox_token)), dl.VideoOverlay(id=VIDEO_OVERLAY_ID, url="/assets/patricia_nasa.webm", bounds=[[32, -130], [13, -100]]), ]), html.Button(id=BUTTON_PLAY_ID, children="Play/pause"), ]
def dpt_color_opacity(opacity_level): ''' This callback takes as input the opacity level chosen by the user on the slider and reinstantiates the colorbar and geojson objects accordingly. These new objects are then injected in the map's children attribute. ''' colorbar, geojson = build_risks_geojson_and_colorbar( opacity_level=opacity_level) return [ dl.TileLayer(id='tile_layer'), geojson, colorbar, build_info_object(app_page='risks'), build_legend_box(app_page='risks'), html.Div(id='fire_markers_risks' ) # Will contain the past fire markers of the risks map ]
def render_example3(): return [ html.H1("Example 3: ImageOverlay"), dl.Map( style={ 'width': '1000px', 'height': '500px' }, bounds=[[40.712216, -74.22655], [40.773941, -74.12544]], children=[ dl.TileLayer(), dl.ImageOverlay( opacity=0.5, url= "https://raw.githubusercontent.com/thedirtyfew/dash-leaflet/master/assets/newark_nj_1922.jpg", bounds=[[40.712216, -74.22655], [40.773941, -74.12544]]) ]), ]
def get_component(eq_data, sizes, opacities, color_params=None, show_uncertainties=False, show_faults=False): """Return the map component with earthquakes represented as circles. Keyword arguments: eq_data -- EarthquakeData object containing the quakes to be drawn. sizes -- An array containing a size for each data point opacities -- An array containing an opacity for each data point color_params -- A tuple with the column name and its minimum and maximum values for extracting and normalizing values to use for colors show_uncertainties -- A boolean indicating whether to display the uncertainties in location of each data point show_faults -- A boolean indicating whether to show the faults """ colors, color_domain = get_colors(eq_data.data, color_params) return dl.Map(id='quake-map', center=eq_data.get_map_center(), zoom=eq_data.get_initial_zoom(), children=[ dl.TileLayer(url=api_url, attribution=attribution), html.Div(id='test-id', children=[ get_fault_layer(show_faults), get_event_layer(eq_data, sizes, colors, opacities), get_location_uncertainty_layer( eq_data, show_uncertainties) ]), (color_domain is not None and dl.Colorbar(width=200, height=20, **color_domain, style={ 'color': 'black', 'font-weight': 'bold' })) ])
def build_alerts_map(): map_object = dl.Map( center=[ 46.5, 2 ], # Determines the point around which the map is initially centered zoom=6, # Determines the initial level of zoom around the center point children=[ dl.TileLayer(id='tile_layer'), build_departments_geojson(), build_info_object(app_page='alerts'), build_legend_box(app_page='alerts'), build_sites_markers(), html.Div(id="live_alerts_marker"), html.Div(id='fire_markers_alerts') ], # Will contain the past fire markers of the alerts map style=map_style, # Reminder: map_style is imported from utils.py id='map') return map_object
def render_example2(): return [ html.H1("Example 2: WMSTileLayer"), dl.Map( style={ 'width': '1000px', 'height': '500px' }, center=[40, -100], zoom=4, children=[ dl.TileLayer(url=mapbox_url.format(id="dark-v9", access_token=mapbox_token)), dl.WMSTileLayer( url= "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", layers="nexrad-n0r-900913", format="image/png", transparent=True), ]) ]
def update_raster_layers_colobar_map_bounds(title): ranges = [data[title][year]['range'] for year in data[title].keys()] lowers, uppers = list(zip(*ranges)) stretch_range = [min(lowers), max(uppers)] xyz = '{z}/{x}/{y}' layers = [] for year in data[title]: raster_data = data[title][year] colormap = raster_data['metadata']['colormap'] bounds = format_bounds(raster_data['bounds']) layers.append( dl.TileLayer( url= f'/singleband/{title}/{year}/{xyz}.png?colormap={colormap}', opacity=0, id=year)) colorbar = get_colorbar(stretch_range, colormap) return layers, [colorbar], bounds
def change_color_opacity(opacity_level): """ -- Managing color opacity in the choropleth map -- This callback takes as input the opacity level chosen by the user on the slider. It then reinstantiates the colorbar and geojson objects accordingly. These new objects are finally returned into the risks map's children attribute. """ colorbar, geojson = build_risks_geojson_and_colorbar( opacity_level=opacity_level) return [ dl.TileLayer(id='tile_layer'), geojson, colorbar, build_info_object(map_type='risks'), build_legend_box(map_type='risks'), html.Div(id='fire_markers_risks' ), # Will contain the past fire markers of the risks map html.Div(id='live_alerts_marker') ]
def update_map(viewData, derived_virtual_selected_rows): """ functionality for updating map. map always shows location of the animal at top of table's current page """ dff = df if viewData is None else pd.DataFrame(viewData) selected_animal = None # if there are no selected rows yet, map default displays first animal of table's current page if not derived_virtual_selected_rows: selected_animal = dff.iloc[0] # else there is a selected row, map displays that animal else: selected_animal = dff.iloc[derived_virtual_selected_rows[0]] latitude = selected_animal[12] longitude = selected_animal[13] animal_breed = selected_animal[3] animal_name = selected_animal[8] return [ dl.Map( style={ 'width': '700px', 'height': '500px' }, center=[latitude, longitude], zoom=10, children=[ dl.TileLayer(id="base-layer-id"), # Marker with tool tip and popup dl.Marker( position=[latitude, longitude], children=[ # show breed of animal on hovering over marker dl.Tooltip(animal_breed), # show animal name on clicking marker dl.Popup([html.H1("Animal Name"), html.P(animal_name)]) ]) ]) ]
def build_risks_map(): geojson, colorbar = build_risks_geojson_and_colorbar() map_object = dl.Map( center=[ 46.5, 2 ], # Determines the point around which the map is initially centered zoom=6, # Determines the initial level of zoom around the center point children=[ dl.TileLayer(id='tile_layer'), geojson, colorbar, build_info_object(app_page='risks'), build_legend_box(app_page='risks'), html.Div(id='fire_markers_risks' ) # Will contain past fire markers of the risks map ], style=map_style, # Reminder: map_style is imported from utils.py id='map') return map_object
def build_risks_map(): """ This function mobilises functions defined hereabove or in the utils module to instantiate and return a dl.Map object, corresponding to the "Risk Score" view. """ geojson, colorbar = build_risks_geojson_and_colorbar() map_object = dl.Map(center=[46.5, 2], # Determines the point around which the map is initially centered zoom=6, # Determines the initial level of zoom around the center point children=[dl.TileLayer(id='tile_layer'), geojson, colorbar, build_filters_object(map_type='risks'), build_legend_box(map_type='risks'), html.Div(id='fire_markers_risks'), # Will contain past fire markers of the risks map html.Div(id='live_alerts_marker') ], style=map_style, # Reminder: map_style is imported from utils.py id='map') return map_object
def plot_coordinate(value='11 Cadogan Gardens'): search_data = df[df['Hotel_Name'] == value] lat = search_data.lat.values[0] lng = search_data.lng.values[0] name = search_data.Hotel_Name.values[0] address_ = search_data.Hotel_Address.values[0] markers = [ dl.Marker( position=[lat, lng], children=[dl.Popup('Name: ' + name + ', Address: ' + address_, )]) ] return html.Div([ dl.Map([dl.TileLayer(), dl.LayerGroup(id="layer")] + [dl.LayerGroup(markers)], center=[lat, lng], zoom=14, id="map", style=MAP_STYLE), ]),
###Main graphs html.Div( id = "main-body", children = [ html.Div( id = "wrapper", children = [ html.Div( id = "map", children = [ dl.Map( center = [-16, -52], zoom = 4, children = [ dl.TileLayer(), geojson, colorbar, html.Div( children = get_info(), id = "info", className = "info", style = {"position": "absolute", "top": "10px", "right": "10px", "z-index": "1000"})], style = {"border-radius":"8px"}) ], className ="leaflet-map"), html.Div( children = dt.DataTable( id = "data_table", columns=[{"id": " ", "name": " "}, {"id": "count", "name": "Observado"},
def render_example1(): comment = """ Marker with default icon, marker with custom icon, circle marker (fixed pixel radius), circle (fixed physical radius), polyline, polygon and rectangle, all supporting tooltips and popups. """ return [ html.H1("Example 1: Basic components"), html.P(comment), dl.Map( id=MAP_ID, style={ 'width': '1000px', 'height': '500px' }, center=[56.05, 10.25], zoom=10, children=[ dl.TileLayer(id=BASE_LAYER_ID), # Marker with tool tip and popup. dl.Marker(position=[56, 9.8], children=[ dl.Tooltip("Marker tooltip"), dl.Popup([ html.H1("Marker popup"), html.P("with inline html") ]) ]), # Marker with custom icon. dl.Marker(position=[55.94, 9.96], icon={ "iconUrl": "/assets/149059.svg", "iconSize": [25, 25] }, children=[dl.Tooltip("Marker with custom icon")]), # Circle marker (with fixed radius in pixel). dl.CircleMarker(center=[56.05, 10.15], radius=20, children=[dl.Popup('Circle marker, 20px')]), # Circle with fixed radius in meters. dl.Circle(center=[56.145, 10.21], radius=2000, color='rgb(255,128,0)', children=[dl.Tooltip('Circle, 2km radius')]), # Polyline marker. dl.Polyline(id='polyline', positions=[[56.06, 10.0], [56.056, 10.01], [56.064, 10.028], [56.0523, 10.0717], [56.044, 10.073]], children=[dl.Tooltip('Polyline')]), # Polygon marker. dl.Polygon(id='polygon', positions=[[56.013, 9.84], [56.0544, 9.939], [56.003, 10.001]], children=[dl.Tooltip('Polygon')]), # Rectangle marker. dl.Rectangle(id='rectangle', bounds=[[55.9, 10.2], [56.0, 10.5]], children=[dl.Tooltip('Rectangle')]) ]), dcc.RadioItems(id=BASE_LAYER_DROPDOWN_ID, options=[{ "label": i, "value": mapbox_url.format(id=i, access_token=mapbox_token) } for i in mapbox_ids], labelStyle={'display': 'inline-block'}, value=mapbox_url.format(id="light-v9", access_token=mapbox_token)), html.P("Coordinate (click on map):"), html.Div(id=COORDINATE_CLICK_ID), ]