Exemplo n.º 1
0
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")
    ]
Exemplo n.º 2
0
def build_geojson_counties(color_prop=None):
    id = 'geojson_counties'
    url = ASSETS['geojson_counties']
    zoomToBounds = False
    zoomToBoundsOnClick = False

    if color_prop:
        hideout = dict(classes=PROPERTIES[color_prop]['classes'],
                       color_prop=color_prop,
                       colorscale=PROPERTIES[color_prop]['color_scale'],
                       style=GEOJSON_COUNTIES_STYLE_1)
        # hoverStyle = GEOJSON_HOVER_STYLE_2
        hoverStyle = None
        options = dict(style=dlx.choropleth.style)
    else:
        hideout = dict()
        # hoverStyle = GEOJSON_HOVER_STYLE_1
        hoverStyle = None
        options = dict(style=GEOJSON_COUNTIES_STYLE_1)

    return dl.GeoJSON(hideout=hideout,
                      id=id,
                      hoverStyle=hoverStyle,
                      options=options,
                      url=url,
                      zoomToBounds=zoomToBounds,
                      zoomToBoundsOnClick=zoomToBoundsOnClick)
Exemplo n.º 3
0
def get_map_panel_zip_layout():
    classes = [0, 100, 500, 1000, 2000, 5000, 10000, 20000]
    colorscale = [
        "#FFEDA0",
        "#FED976",
        "#FEB24C",
        "#FD8D3C",
        "#FC4E2A",
        "#E31A1C",
        "#BD0026",
        "#800026",
    ]
    style = {
        "weight": 2,
        "opacity": 1,
        "color": "white",
        "dashArray": 3,
        "fillOpacity": 0.7,
    }

    ctg = ["{}+".format(cls, classes[i + 1]) for i, cls in enumerate(classes[:-1])] + [
        "{}+".format(classes[-1])
    ]
    colorbar = dlx.categorical_colorbar(
        categories=ctg,
        colorscale=colorscale,
        width=400,
        height=30,
        position="bottomright",
    )

    ns = Namespace("dlx", "choropleth")
    zip_geojson = dl.GeoJSON(
        data=None,  # url to geojson file
        options=dict(style=ns("style")),  # how to style each polygon
        zoomToBounds=False,  # when true, zooms to bounds when data changes (e.g. on load)
        zoomToBoundsOnClick=True,  # when true, zooms to bounds of feature (e.g. polygon) on click
        hoverStyle=arrow_function(
            dict(weight=5, color="#666", dashArray="")
        ),  # style applied on hover
        hideout=dict(
            colorscale=colorscale, classes=classes, style=style, colorProp="Amount"
        ),
        id="zips-geojson",
    )

    stl_center = [38.648, -90.253]
    city_map_style = {"height": "100vh", "margin": "none", "display": "block"}
    city_map = html.Div(
        dl.Map(
            children=[get_base_toner_tile_layer(), zip_geojson, colorbar],
            zoom=12,
            center=stl_center,
        ),
        style=city_map_style,
        id="map",
    )
    map_panel_style = {"width": "100%", "height": "100vh", "display": "block"}
    map_panel = html.Div(id="map-panel", children=city_map, style=map_panel_style)
    return map_panel
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")
Exemplo n.º 5
0
def build_geojson_states():
    id = 'geojson_states'
    options = dict(style=GEOJSON_STATES_STYLE_1)
    url = ASSETS['geojson_states']
    zoomToBounds = False
    zoomToBoundsOnClick = False

    return dl.GeoJSON(id=id,
                      options=options,
                      zoomToBounds=zoomToBounds,
                      zoomToBoundsOnClick=zoomToBoundsOnClick,
                      url=url)
Exemplo n.º 6
0
def get_neighborhood_geojson():
    ns = Namespace("dlx", "choropleth")
    neighborhoods_geobuf_path = "static/geobuf/neighborhoods-and-municipalities.pbf"
    neighborhoods_geojson = dl.GeoJSON(
        format="geobuf",
        options=dict(style=ns("style")),
        hoverStyle=arrow_function(dict(weight=5, color="#666", dashArray="")),
        hideout=bootstrap_stuff.build_choropleth_hideout(
            "total_monetary_donations"),
        id="neighborhood-geojson",
    )
    return neighborhoods_geojson
Exemplo n.º 7
0
def get_precinct_geojson():
    ns = Namespace("dlx", "choropleth")
    precincts_geobuf_path = "dsadata/static/geobuf/stl-city-and-county-precincts.pbf"
    precincts_geojson = dl.GeoJSON(
        format="geobuf",
        options=dict(style=ns("style")),
        hoverStyle=arrow_function(dict(weight=5, color="#666", dashArray="")),
        hideout=bootstrap_stuff.build_choropleth_hideout(
            "total_monetary_donations"),
        id="precincts-geojson",
    )
    return precincts_geojson
Exemplo n.º 8
0
def get_neighborhood_geojson():
    ns = Namespace("dlx", "choropleth")
    neighborhoods_geojson = dl.GeoJSON(
        format="geobuf",
        options=dict(style=ns("style")),
        hoverStyle=arrow_function(dict(weight=5, color="#666", dashArray="")),
        zoomToBoundsOnClick=
        False,  # when true, zooms to bounds of feature (e.g. polygon) on click
        hideout=bootstrap_stuff.build_choropleth_hideout(
            "total_monetary_donations"),
        id="neighborhood-geojson",
    )
    return neighborhoods_geojson
Exemplo n.º 9
0
def build_departments_geojson():
    """
    This function reads the departments.geojson file in the /data folder thanks to the json module
    and returns an interactive dl.GeoJSON object containing its information, to be displayed on the map.
    """

    # We plug departments in a Dash Leaflet GeoJSON object that will be added to the map
    geojson = dl.GeoJSON(data=departments,
                         id='geojson_departments',
                         zoomToBoundsOnClick=False,
                         hoverStyle=dict(weight=3, color='#666', dashArray=''))

    # We simply return the GeoJSON object for now
    return geojson
Exemplo n.º 10
0
def get_precinct_overlay():
    # original file was wrong hand rule, whis one was rewound with geojson-rewind:
    precinct_geojson_path = "data/geojson/stl-city/precincts_rw.geojson"
    with open(precinct_geojson_path) as read_file:
        precinct_geojson = json.load(read_file)
    precincts = dl.GeoJSON(
        data=precinct_geojson,
        options=dict(style=dict(color="blue", fillOpacity=0.5)),
        zoomToBoundsOnClick=True,
        hoverStyle=arrow_function(dict(weight=4, fillOpacity=0.2, dashArray="")),
        id="precincts-geojson",
    )
    precinct_overlay = dl.Overlay(precincts, name="precincts", checked=False)
    return precinct_overlay
Exemplo n.º 11
0
def geojson(data, *args, style, **kwargs):
    feature_id = "id"
    # If id missing and/or not unique, a new id (this list index) is assigned (this is NOT recommended).
    if not _validate_feature_ids(data):
        feature_id = "dash_id"
        for i, f in enumerate(data["features"]):
            f[feature_id] = i
    # Setup style.
    feature_style = {f[feature_id]: style(f) for f in data["features"]}
    return dl.GeoJSON(*args,
                      data=data,
                      featureStyle=feature_style,
                      featureId=feature_id,
                      **kwargs)
Exemplo n.º 12
0
def get_precinct_overlay():
    # original file was wrong hand rule, whis one was rewound with geojson-rewind:
    precinct_pbf_url = "dsadata/static/geobuf/stl-city-precincts.pbf"
    ns = Namespace("dlx", "choropleth")
    precincts = dl.GeoJSON(
        url=precinct_pbf_url,
        format="geobuf",
        options=dict(style=ns("style")),
        zoomToBoundsOnClick=True,
        hoverStyle=arrow_function(dict(weight=4, fillOpacity=0.2,
                                       dashArray="")),
        hideout=bootstrap_stuff.build_choropleth_hideout("total_donations"),
        id="precincts-geojson",
    )
    precinct_overlay = dl.Overlay(precincts, name="precincts", checked=False)
    return precinct_overlay
Exemplo n.º 13
0
def get_zip_geojson():
    ns = Namespace("dlx", "choropleth")
    zip_geojson = dl.GeoJSON(
        format="geobuf",
        options=dict(style=ns("style")),  # how to style each polygon
        # options=dict(style=dict(color="blue")),
        zoomToBounds=
        False,  # when true, zooms to bounds when data changes (e.g. on load)
        zoomToBoundsOnClick=
        False,  # when true, zooms to bounds of feature (e.g. polygon) on click
        hoverStyle=arrow_function(dict(weight=5, color="#666", dashArray="")),
        hideout=bootstrap_stuff.build_choropleth_hideout(
            "total_monetary_donations"),
        id="zip-geojson",
    )
    return zip_geojson
Exemplo n.º 14
0
def build_departments_geojson():

    # We fetch the json file online and store it in the departments variable
    with open(
            Path(__file__).parent.joinpath('data', 'departements.geojson'),
            'rb') as response:
        departments = json.load(response)

    # We plug departments in a Dash Leaflet GeoJSON object that will be added to the map
    geojson = dl.GeoJSON(data=departments,
                         id='geojson_departments',
                         zoomToBoundsOnClick=True,
                         hoverStyle=dict(weight=3, color='#666', dashArray=''))

    # We simply return the GeoJSON object for now
    return geojson
Exemplo n.º 15
0
def build_risks_geojson_and_colorbar(opacity_level=0.75):
    """
    This function creates the main attributes specific to the choropleth map.

    It simply takes as input an opacity level, which defaults to 0.75, for coloring the departments.

    It returns:

    - a dl.GeoJSON object that allows to displays the departments' boundaries and respective risk score categories;
    - a colorbar object that distinguishes, as shades of yellow and red, 8 categories of risk score from 0 to 1.
    """

    # First step is to prepare the choropleth map by building the color scale corresponding to score risks
    # To define 8 risk levels between 0 and 1, we need to choose 9 floats that will serve as borders
    classes = np.linspace(0, 1, 9)

    # We choose 8 shades of yellow and red to define our color scale
    colorscale = ['#FFEDA0', '#FED976', '#FEB24C', '#FD8D3C', '#FC4E2A', '#E31A1C', '#BD0026', '#800026']

    # We create a 'categories' object of the right format, then plug it into the Dash Leaflet
    # function instantiating the colorbar
    ctg = ["{}+".format(round(cls, 2)) for i, cls in enumerate(classes[:-1])]
    colorbar = dlx.categorical_colorbar(categories=ctg, colorscale=colorscale, width=500, height=30,
                                        position="bottomleft")

    # We define the style of department delimitations on the map
    # (opacity and color of borders, opacity of color backgrounds...)
    scale_style = dict(weight=2, opacity=0.9, color='white', dashArray='3', fillOpacity=opacity_level)

    # We finally instantiate the dl.GeoJSON object that will be attributed to the "Niveaux de Risque" map
    geojson = dl.GeoJSON(data=departments,
                         id='geojson_risks',
                         zoomToBoundsOnClick=True,
                         hoverStyle=dict(weight=3,
                                         color='#666',
                                         dashArray=''),
                         hideout=dict(colorscale=colorscale,
                                      classes=classes,
                                      style=scale_style,
                                      color_prop='score'),
                         options=dict(style=dlx.choropleth.style))

    return geojson, colorbar
Exemplo n.º 16
0
def get_zip_overlay(mec_df, candidate):
    if candidate is not None:
        cand_df = contrib.sum_funds_by_zip(cand_zip_df)
    else:
        df = cand_zip_df[cand_zip_df[" MECID"] == candidate]
    # original file was wrong hand rule, whis one was rewound with geojson-rewind:
    zip_geojson_path = "data/geojson/stl-region-zip_rw.geojson"
    gdf = gpd.read_file(zip_geojson_path)
    gdf = gdf.merge(cand_zip_df, left_on="ZCTA5CE10", right_on="ZIP5")
    if candidate is not None:
        df = contrib.sum_funds_by_zip(cand_zip_df)
    else:
        df = cand_zip_df[cand_zip_df[" MECID"] == candidate]
    with open(zip_geojson_path) as read_file:
        zip_geojson = json.load(read_file)
    zips = dl.GeoJSON(
        data=zip_geojson,
        options=dict(style=dict(color="purple", fillOpacity=0.5)),
        zoomToBoundsOnClick=True,
        hoverStyle=arrow_function(dict(weight=4, fillOpacity=0.2, dashArray="")),
        id="zips-geojson",
    )
    zip_overlay = dl.Overlay(zips, name="zips", checked=True)
    return zip_overlay
Exemplo n.º 17
0
coords_list = []
# Switch lat/lon, and append river coords to coords_list
for coords in river_coords:
    points = []
    for point in coords:
        rev_point = point[::-1]
        points.append(rev_point)
    coords_list.append(points)

# Transform gridded data in right style
grid_geo = dl.GeoJSON(data=grid,
                      id="grid_geojson",
                      options=dict(hoverStyle=dict(weight=5,
                                                   color='#666',
                                                   dashArray=''),
                                   zoomToBoundsOnClick=False,
                                   style=dict(fill=False,
                                              weight=1,
                                              opacity=1,
                                              color='white',
                                              dashArray='3',
                                              fillOpacity=0.1)))
districts_geo = dl.GeoJSON(data=admin_boundaries,
                           id="districts_geojson",
                           options=dict(hoverStyle=dict(weight=5,
                                                        color='#666',
                                                        dashArray=''),
                                        zoomToBoundsOnClick=False,
                                        style=dict(fill=False,
                                                   weight=1,
                                                   opacity=0.8,
                                                   color='black',
Exemplo n.º 18
0
    geobuf = dlx.geojson_to_geobuf(geojson)
    return geobuf


# create cpa dropdown
cpas = df['cpa_name'].unique()
cpa_options = [{'label': cpa, 'value': cpa} for cpa in cpas]
dd_cpa = dcc.Dropdown(options=cpa_options, id='dd_cpa')

# set up scatter points
ns = Namespace('dlx', 'scatter')
geojson = dl.GeoJSON(
    data=get_data(None),
    id='geojson',
    format='geobuf',
    zoomToBounds=True,
    cluster=True,
    #  clusterToLayer=ns("clusterToLayer"),
    zoomToBoundsOnClick=True,
    #  options=dict(pointToLayer=ns('pointToLayer')),
    superClusterOptions=dict(radius=150))
#  hideout=dict(colorscale='Viridis', colorProp='cpa'))

# add cpa boundaries
cpa_boundaries = dl.GeoJSON(
    id='rfmp',
    url="/assets/rfmp4.json",
    zoomToBounds=True,
    hoverStyle=arrow_function(dict(weight=5, color='#666',
                                   dashArray='')))  # must be in assets folder

# create map
Exemplo n.º 19
0
         className="container_title"),
 html.Div(
     [
         dl.Map([
             dl.LayersControl([
                 dl.BaseLayer(
                     dl.TileLayer(url=url_template.format(key),
                                  attribution=attribution),
                     name=key,
                     checked=key == checked_key) for key in keys
             ] + [
                 dl.LayerGroup(id="layer"),
                 dl.GeoJSON(
                     id='polygons',
                     options=dict(style=ns("style")),
                     hideout=dict(colorscale=colorscale,
                                  classes=classes,
                                  style=style,
                                  colorProp="index"),
                 )
             ]),
         ],
                id="map-graph",
                zoom=4,
                center=(39, -100)),
         html.Div(
             [
                 html.H5("Average Speed",
                         style={"color": "#191a1a"}),
                 dcc.Dropdown(id='average-speed',
                              options=[{
                                  'label': i,
Exemplo n.º 20
0
        r"C:\Users\julien_schroder\Desktop\JM_FinaleMaps_Repo\Routes4326.geojson"
) as g:
    routes = geojson.load(g)

dRoutes = FeatureCollection([f for f in routes['features']])
dPoints = FeatureCollection([f for f in points['features']])

biosfera = dlx.geojson_to_geobuf(
    dlx.dicts_to_geojson([dict(lat=29.015, lon=-118.271)]))
app.layout = html.Div([
    dl.Map(
        center=[39, -98],
        zoom=4,
        children=[
            dl.TileLayer(),
            dl.GeoJSON(data=dPoints, id='capitals',
                       cluster=True),  # in-memory geojson (slowest option)
            dl.GeoJSON(data=dRoutes, id='states'
                       ),  # in-memory geobuf (smaller payload than geojson)
        ],
        style={
            'width': '100%',
            'height': '100vh',
            'margin': "auto",
            "display": "block"
        },
        id="map"),
    html.Div(id="state"),
    html.Div(id="capital")
])

Exemplo n.º 21
0
            du.get_col("Amount", year): "Amount",
            du.get_col("Per Capita", year): "Per Capita",
            du.get_col("Per Student", year): "Per Student",
        })


# leaflet map: Create geojson.

geojson = dl.GeoJSON(
    id="geojson",
    format="geobuf",
    zoomToBounds=True,  # when true, zooms to bounds when data changes
    cluster=True,  # when true, data are clustered
    clusterToLayer=dlx.scatter.cluster_to_layer,  # how to draw clusters
    zoomToBoundsOnClick=
    True,  # when true, zooms to bounds of feature (e.g. cluster) on click
    options=dict(
        pointToLayer=dlx.scatter.point_to_layer,
        onEachFeature="window.dash_props.module.on_each_feature",
    ),  # popup in callback, how to draw points
    superClusterOptions=dict(radius=150),  # adjust cluster size
    hideout={},
)
local_map = dl.Map(
    [
        dl.TileLayer(
            url=
            "https://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png"
        ),
        geojson,
    ],
Exemplo n.º 22
0
                        value=default_state,
                        id="dd_state",
                        clearable=False)

# endregion

minmax = get_minmax(default_state)
# Create geojson.
ns = Namespace("dlx", "scatter")
geojson = dl.GeoJSON(
    data=get_data(default_state, [2015, 2020]),
    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']
Exemplo n.º 23
0
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
Exemplo n.º 24
0
default_variable = "temperature"
variable_options = [
    {'label': 'Temp.', 'value': 'temperature'},
    {'label': 'MSLP', 'value': 'smlp'},
    {'label': 'Hum.', 'value': 'rh'},
    {'label': 'Wind Sp.', 'value': 'wind_speed'},
    {'label': 'Wind G.', 'value': 'wind_gust'},
    {'label': 'Rain', 'value': 'rain_rate'},
    {'label': 'Daily Rain', 'value': 'daily_rain'},
    {'label': 'Dewp', 'value': 'dew_point'},
    {'label': 'Rad', 'value': 'rad'},
]


ns = Namespace("myNamespace", "mySubNamespace")
geojson_countries = dl.GeoJSON(data=statesData, id="geojson_countries",
                               options=dict(style=dict(weight=1, opacity=0.7, color='white', fillOpacity=0)))

# Create the app.
chroma = "https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js"
app = Dash(__name__,
           external_scripts=[chroma],
           prevent_initial_callbacks=True,
           url_base_pathname='/weathermap-it/')
server = app.server


cache = Cache(server, config={'CACHE_TYPE': 'filesystem',
                             'CACHE_DIR': '/tmp'})


@cache.memoize(900)
Exemplo n.º 25
0
            className="header",
        ),

        # MAP
        html.Div(
            children=[
                dl.Map(center=[lat_center, long_center],
                       zoom=14,
                       children=[
                           dl.TileLayer(url=url,
                                        attribution=attribution,
                                        maxZoom=20),
                           dl.GeoJSON(
                               data=data,
                               id="unique-squirrel-id",
                               format="geobuf",
                               cluster=True,
                               zoomToBoundsOnClick=True,
                               superClusterOptions={"radius": 50},
                               options=dict(pointToLayer=ns("pointToLayer"))),
                       ],
                       className="squirrel-map",
                       style={'display': 'block'},
                       id="map"),
            ],
            className="squirrel-map-container",
        ),
        # SQUIRREL INFO
        html.Div(id="squirrel-facts"),

        # invisible sound containers
        html.Div(id="placeholder1", style={"display": "none"}),
Exemplo n.º 26
0
from dash.dependencies import Input, Output
from dash_transcrypt import inject_js, module_to_props

# Create some markers.
points = [
    dict(lat=55.5 + random.random(),
         lon=9.5 + random.random(),
         value=random.random()) for i in range(100)
]
data = dlx.dicts_to_geojson(points)
# Create geojson.
js = module_to_props(rjs)  # compiles the js
geojson = dl.GeoJSON(
    data=data,
    options=dict(pointToLayer=rjs.point_to_layer),  # pass function as prop
    hideout=dict(scale=10),
    id="geojson")  # pass variables to function
# Create the app.
app = dash.Dash()
app.layout = html.Div([
    dl.Map([dl.TileLayer(), geojson],
           center=(56, 10),
           zoom=8,
           style={'height': '50vh'}),
    dcc.Slider(min=1, max=100, value=10, id="slider")
])
inject_js(app, js)  # adds the js to the app


@app.callback(Output("geojson", "hideout"), [Input("slider", "value")],
Exemplo n.º 27
0
dicts = df_state.to_dict('rows')
for item in dicts:
    item["tooltip"] = item["city"]  # bind tooltip

geojson = dlx.dicts_to_geojson(dicts, lon="lng")  # convert to geojson
geobuf = dlx.geojson_to_geobuf(geojson)  # convert to geobuf

with open('geobuf.pkl', 'wb') as f:
    pickle.dump(geobuf, f, pickle.HIGHEST_PROTOCOL)

geojson = dl.GeoJSON(
    data=geobuf,
    id="geojson",
    format="geobuf",
    zoomToBounds=True,  # when true, zooms to bounds when data changes
    cluster=True,  # when true, data are clustered
    clusterToLayer=dlx.scatter.cluster_to_layer,  # how to draw clusters
    zoomToBoundsOnClick=
    True,  # when true, zooms to bounds of feature (e.g. cluster) on click
    options=dict(
        pointToLayer=dlx.scatter.point_to_layer),  # how to draw points
    superClusterOptions=dict(radius=150),
    hideout={
        'colorscale': ['green'],
        'color_prop': color_prop,
        'min': 0,
        'max': 0
    })

with open('geojson.pkl', 'wb') as g:
    pickle.dump(geojson, g, pickle.HIGHEST_PROTOCOL)
Exemplo n.º 28
0
circles = []
for idx, point in enumerate(points):
    circle = {
        "key": str(idx),
        "properties": {
            "radius": 10
        },
        "geometry": {
            "type": "Point",
            "coordinates": (center + point).tolist()
        }
    }
    circles.append(circle)

circles = json.dumps(circles)

app = dash.Dash()
app.layout = html.Div([
    dl.Map(style={
        'width': '1000px',
        'height': '500px'
    },
           center=center,
           zoom=10,
           children=[dl.TileLayer(), dl.GeoJSON(data=circles)])
])

if __name__ == '__main__':
    app.run_server(debug=True, port=8053)
Exemplo n.º 29
0
quantiles = [int(n) for n in quantiles.values]

classes = quantiles
colorscale = ['#FED976', '#FEB24C', '#FD8D3C', '#FC4E2A', '#800026']
style = dict(weight=2, opacity=1, color='white', dashArray='3', fillOpacity = 0.7)

# Create colorbar.
ctg = ["{}+".format(cls, classes[i + 1]) for i, cls in enumerate(classes[:-1])] + ["{}+".format(classes[-1])]
colorbar = dlx.categorical_colorbar(categories=ctg, colorscale=colorscale, width=300, height=30, position="bottomleft")

ns = Namespace("dlx", "choropleth")
### Define layouts
geojson = dl.GeoJSON(
    data = json_data,
    options=dict(style=ns("style")),
    zoomToBoundsOnClick = False,
    hoverStyle=arrow_function(dict(weight=2, color='#666', dashArray='', fillOpacity=0.2)),  # style applied on hover
    hideout=dict(colorscale=colorscale, classes=classes, style=style, colorProp = "cases"),
    id = "geojson")




cont = dbc.Card(
    [
        dbc.CardImg(src = "assets/form.svg", top = True, className = "card-img"),
        dbc.CardBody(
            [
                html.P(
                    "Casos: " + str(conf.return_data_size())
                )
Exemplo n.º 30
0
        20: "20",
        30: "30",
        40: "40",
        50: "50"
    },
    disabled=disable_odlines(default_zoomed),
    id="sl_line",
)

# Create geojson foreground.
style_hover = {"weight": 5, "color": "#666", "dashArray": ""}
ns = Namespace("dlx", "choropleth")
geojson_fg = dl.GeoJSON(
    url=get_url_fg(default_zoomed, default_region, default_name),
    format="geobuf",
    options=dict(style=ns("style")),  # how to style each polygon
    hideout=get_hideout(default_case),
    zoomToBoundsOnClick=True,  # when true, zooms to bounds of feature on click
    hoverStyle=arrow_function(style_hover),
    id="geojson_fg")

# Create geojson background.
style_bg = {
    "weight": 2,
    "opacity": 1,
    "color": "white",
    "dashArray": 3,
    "fillOpacity": 0.5
}
geojson_bg = dl.GeoJSON(
    url=get_url_bg(default_zoomed, default_region, default_name),
    format="geobuf",