Beispiel #1
0
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)
            ]),
    ]
Beispiel #2
0
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)
            ]),
    ]
Beispiel #3
0
def categorical_colorbar(*args, categories, colorscale, **kwargs):
    indices = list(range(len(categories) + 1))
    return dl.Colorbar(*args,
                       min=0,
                       max=len(categories),
                       classes=indices,
                       colorscale=colorscale,
                       tooltip=False,
                       tickValues=[item + 0.5 for item in indices[:-1]],
                       tickText=categories,
                       **kwargs)
Beispiel #4
0
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 serve_layout():
    dd_variable = dcc.Dropdown(options=variable_options,
                               value=default_variable, id="dd_variable", clearable=False)
    minmax = get_minmax(default_variable)
    # # Create a colorbar.
    colorbar = dl.Colorbar(
        colorscale=csc_map[default_csc], id="colorbar", width=20, height=150, **minmax)
    
    geojson = dl.GeoJSON(data=get_data(default_variable), id="geojson",
                         format='geobuf',
                         cluster=True,  # when true, data are clustered
                         # how to draw clusters
                         clusterToLayer=ns("clusterToLayer"),
                         # how to draw points
                         options=dict(pointToLayer=ns("pointToLayer")),
                         superClusterOptions=dict(radius=50),  # adjust cluster size
                         hideout=dict(colorscale=csc_map[default_csc],
                                      colorProp=default_variable, **minmax))

    times = pd.date_range(start=pd.to_datetime('now', utc=True).round('15min') - pd.Timedelta('2hours'),
                          end=pd.to_datetime('now', utc=True).round(
                              '15min') - pd.Timedelta('15min'),
                          freq='5min')
    latest = times[-1].strftime('%Y-%m-%dT%H:%M:00.000Z')

    numdate = [x for x in range(len(times))]
    marks = {numd: date.strftime('%H:%M')
             for numd, date in zip(numdate, times)}

    slider = dcc.Slider(id='time_slider', min=numdate[0],
                        max=numdate[-1],
                        value=numdate[-1],
                        marks=marks)

    layout = html.Div([
        dl.Map([
            dl.LayersControl(
                [
                    dl.BaseLayer(dl.TileLayer(url=mapURL, attribution=attribution,
                                              tileSize=512, zoomOffset=-1), name='map', checked=True),
                    dl.Overlay(dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?",
                                               layers="dwd:SAT_EU_RGB",
                                               format="image/png",
                                               transparent=True, opacity=0.6,
                                               version='1.3.0',
                                               detectRetina=True), name='sat eu', checked=True),
                    dl.Overlay(dl.WMSTileLayer(id='radar_it',
                                               url="http://www.protezionecivile.gov.it/geowebcache/service/wms?tiled=True&time=%s" % latest,
                                               layers="radar:vmi",
                                               transparent=True,
                                               format="image/png",
                                               opacity=1.0,
                                               version='1.1.1'),
                      name='radar IT', checked=True),
                    dl.Overlay([geojson, colorbar], name='obs', checked=True)
                ]),
            geojson_countries,
        ], center=[41, 12], zoom=6),
        html.Div(id='date-div', style={'display': 'none'},
                 children=times.strftime('%Y-%m-%dT%H:%M:00.000Z')),
        html.Div([slider],
                 style={"position": "absolute", "bottom": "20px",
                        "left": "10px", "z-index": "1000", "width": "800px",
                        "background-color": 'rgba(1, 1, 1, 0.3)'}),
        html.Div([dd_variable],
                 style={"position": "absolute", "top": "300px", "right": "16px", "z-index": "1000", "width": "100px"})
    ], style={'width': '100%', 'height': '90vh', 'margin': "auto", "display": "block", "position": "relative"})

    return layout
Beispiel #6
0
    id="geojson",
    format="geobuf",
    zoomToBounds=True,  # when true, zooms to bounds when data changes
    cluster=True,  # when true, data are clustered
    clusterToLayer=ns("clusterToLayer"),  # how to draw clusters
    zoomToBoundsOnClick=
    True,  # when true, zooms to bounds of feature (e.g. cluster) on click
    options=dict(pointToLayer=ns("pointToLayer")),  # how to draw points
    superClusterOptions=dict(radius=150),  # adjust cluster size
    hideout=dict(colorscale=csc_map[default_csc],
                 colorProp=color_prop,
                 **minmax))
# Create a colorbar.
colorbar = dl.Colorbar(colorscale=csc_map[default_csc],
                       id="colorbar",
                       width=20,
                       height=150,
                       **minmax)
# Create the app.
chroma = "https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js"
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = Dash(__name__,
           meta_tags=[{
               "name": "viewport",
               "content": "width=device-width, initial-scale=1.0"
           }],
           external_scripts=[chroma],
           external_stylesheets=external_stylesheets,
           prevent_initial_callbacks=False)

app.layout = html.Div([
srng0 = srng_map[param0]
# App Stuff.
server = Flask(__name__)
app = dash.Dash(__name__, server=server)
app.layout = html.Div(
    children=[
        # Create the map itself.
        dl.Map(id="map",
               center=[56, 10],
               zoom=7,
               children=[
                   dl.TileLayer(),
                   dl.TileLayer(id="tc", opacity=0.5),
                   dl.Colorbar(id="cbar",
                               width=150,
                               height=20,
                               style={"margin-left": "40px"},
                               position="bottomleft"),
               ],
               style={
                   "width": "100%",
                   "height": "100%"
               }),
        # Create controller.
        html.Div(children=[
            html.Div("Parameter"),
            dcc.Dropdown(
                id="dd_param",
                options=[dict(value=p, label=lbl_map[p]) for p in PARAMS],
                value=param0),
            html.Br(),
Beispiel #8
0
def serve_layout():
    minmax = get_minmax(default_variable)

    # Create a colorbar.
    colorbar = dl.Colorbar(colorscale=csc_map[default_csc],
                           id="colorbar",
                           width=20,
                           height=150,
                           **minmax)

    geojson = dl.GeoJSON(
        data=get_data(default_variable),
        id="geojson",
        format="geobuf",
        zoomToBounds=True,  # when true, zooms to bounds when data changes
        cluster=True,  # when true, data are clustered
        # how to draw clusters
        clusterToLayer=ns("clusterToLayer"),
        # when true, zooms to bounds of feature (e.g. cluster) on click
        zoomToBoundsOnClick=True,
        # how to draw points
        options=dict(pointToLayer=ns("pointToLayer")),
        superClusterOptions=dict(radius=20),  # adjust cluster size
        hideout=dict(colorscale=csc_map[default_csc],
                     colorProp=default_variable,
                     **minmax))

    layout = html.Div(
        [
            dl.Map([
                dl.LayersControl([
                    dl.BaseLayer(dl.TileLayer(url=mapURL,
                                              attribution=attribution,
                                              tileSize=512,
                                              zoomOffset=-1),
                                 name='map',
                                 checked=True),
                    dl.Overlay(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),
                               name='sat world',
                               checked=True),
                    dl.Overlay(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),
                               name='sat eu',
                               checked=True),
                    dl.Overlay(dl.WMSTileLayer(
                        url="https://maps.dwd.de/geoserver/ows?",
                        layers="dwd:WN-Produkt",
                        format="image/png",
                        transparent=True,
                        opacity=0.7,
                        version='1.3.0',
                        detectRetina=True),
                               name='radar DE',
                               checked=True),
                    dl.Overlay(
                        [geojson, colorbar], name='obs DE', checked=True)
                ]),
                geojson_countries,
            ]),
            html.Div(
                [dd_variable, dd_csc],
                style={
                    "position": "relative",
                    "bottom": "80px",
                    "left": "10px",
                    "z-index": "1000",
                    "width": "200px"
                })
        ],
        style={
            'width': '100%',
            'height': '90vh',
            'margin': "auto",
            "display": "block",
            "position": "relative"
        })

    return layout
Beispiel #9
0
def generate_choropleth(metric, violation, subcategory, year):
    """Updates the choropleth map on tab 1 when triggered
    
    Parameters
    -------
    String
        The name of the metric selected from the dropdown
    String
        The violation selected from the dropdown
    String
        The subcategory selected from the dropdown
    Int
        The year selected from the slider
    
    Returns
    -------
    html
        A leaflet choropleth map
    """

    geojson = PROVINCES
    df = DATA[(DATA["Metric"] == metric)
              & (DATA["Level1 Violation Flag"] == violation) &
              (DATA["Violation Description"] == subcategory) &
              (DATA["Year"] == year) & (DATA['Geo_Level'] == "PROVINCE")]

    data_dict = dict(zip(df['Geography'], df['Value']))

    for location in geojson['features']:
        try:
            lookup_val = data_dict[location['properties']['PRENAME']]
        except:
            lookup_val = None
        location['properties']['Value'] = lookup_val

    num = 13  # number of provinces and territories in Canada
    vals = pd.Series(data_dict.values())
    classes = list(
        np.linspace(int(vals.min()) - 0.01, int(vals.max()) + 0.01, num=num))
    mm = dict(min=vals.min(), max=vals.max())

    viridis = cm.get_cmap('viridis', num)
    colorscale = []
    for i in range(viridis.N):
        rgba = viridis(i)
        colorscale.append(matplotlib.colors.rgb2hex(rgba))

    style = dict(weight=1, color='black', fillOpacity=0.7)
    hover_style = dict(weight=5, color='orange', dashArray='')
    ns = Namespace("dlx", "choropleth")

    return [
        dl.TileLayer(),
        dl.GeoJSON(data=geojson,
                   id="provinces",
                   options=dict(style=ns("style")),
                   hideout=dict(colorscale=colorscale[::-1],
                                classes=classes,
                                style=style,
                                colorProp="Value"),
                   hoverStyle=arrow_function(hover_style)),
        dl.Colorbar(colorscale=colorscale[::-1],
                    id="colorbar",
                    width=20,
                    height=150,
                    **mm,
                    position="bottomleft")
    ]