def create_fault_layer(): blind_faults = shapefile.Reader(faults_blind) nonblind_faults = shapefile.Reader(faults_nonblind) faults = [ dl.Polyline( color='#404040', weight=1.25, dashArray='2, 3', positions=[[ coord[1], coord[0] ] for coord in feature.shape.__geo_interface__['coordinates']]) for feature in blind_faults.shapeRecords() ] faults += [ dl.Polyline( color='black', weight=1, positions=[[ coord[1], coord[0] ] for coord in feature.shape.__geo_interface__['coordinates']]) for feature in nonblind_faults.shapeRecords() ] return dl.LayerGroup(id='fault-layer', children=faults)
def map_click(click_lat_lng, n_clicks, data, polygons): trigger = dash.callback_context.triggered[0]["prop_id"] print(trigger) # The map was clicked, add a new point. if trigger.split(".")[1] == "click_lat_lng": if len(polygons) > 0: for polygon in polygons: # print(polygon['props']['positions']) sg_poly = sg.Polygon(polygon['props']['positions']) if (sg.Point(float(click_lat_lng[0]), float(click_lat_lng[1])).within(sg_poly)): print('you are within existing polygon') return data, '', polygons data.append(click_lat_lng) markers = [ dl.CircleMarker(center=pos, id={ 'role': 'marker', 'index': i }) for i, pos in enumerate(data) ] polyline = dl.Polyline(positions=data) drawing = markers + [polyline] # A marker was clicked, close the polygon and reset drawing. else: polygons.append(dl.Polygon(positions=data)) data, drawing = [], [] print(data, drawing, polygons) return data, drawing, polygons
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 update_output(value): # print(sorted_df.area_name_en.str.contains(value)) # filtered_df = sorted_df[sorted_df['area_name_en'].str.contains(value)] s = sorted_df sales_dt = sorted_df.groupby(['instance_date'])['index']\ .count().reset_index(name="count_col") overview_x = sales_dt.instance_date.to_list() overview_y = sales_dt.count_col.to_list() average_sales = sorted_df.groupby('instance_date')['meter_sale_price']\ .mean().reset_index(name="meter_sale_price") average_x = average_sales['instance_date'].to_list() average_y = average_sales['meter_sale_price'].to_list() if value: polyline = None pos_data = [] s = sorted_df[sorted_df.area_name_en == value] sales_dt = s.groupby(['instance_date'])['index']\ .count().reset_index(name="count_col") overview_x = sales_dt.instance_date.to_list() overview_y = sales_dt.count_col.to_list() average_sales = s.groupby('instance_date')['meter_sale_price']\ .mean().reset_index(name="meter_sale_price") average_x = average_sales['instance_date'].to_list() average_y = average_sales['meter_sale_price'].to_list() res = api.query(district_query.format(value)) if len(res.ways): for node in res.ways[0].nodes: pos_data.append([node.lat, node.lon]) polyline = dl.Polyline(positions=pos_data) return polyline, pos_data, px.line( x=overview_x, y=overview_y, labels={'x': 'Date', 'y': 'Sales'} ), px.line( x=average_x, y=average_y, labels={'x': 'Date', 'y': 'Sales Price'} ) return None, sample_bounds, px.line( x=overview_x, y=overview_y, labels={'x': 'Date', 'y': 'Sales'} ), px.line( x=average_x, y=average_y, labels={'x': 'Date', 'y': 'Sales Price'} )
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 get_location_uncertainty_layer(eq_data, visible): """Return a map layer with uncertainties visualized for each data point. Keyword arguments: eq_data -- An Earthquake data object containing the data visible on the map visible -- A boolean indicating whether to display the uncertainties in location of each data point """ if eq_data.data.shape[0] == 0 or not visible: return dl.LayerGroup(id='location-uncertainties') location_uncertainties = eq_data.get_location_uncertainties() reset_data = eq_data.data.reset_index() uncertainties = [] if type(location_uncertainties) == int: uncertainties = [ dl.Circle(center=[quake['LATITUDE'], quake['LONGITUDE']], radius=location_uncertainties, color='black', fillOpacity=0, dashArray='5, 5', weight=1.5, children=[ dl.Popup(dcc.Markdown( list( map( lambda x: '**{}**: {} '.format( x.replace('[', r'\['), quake[x]), quake.keys()))), className='earthquake-popup') ]) for _, quake in reset_data.iterrows() ] else: uncertainties += [ dl.Polyline(positions=[[ quake['LATITUDE'], quake['LONGITUDE'] ], location_uncertainties[idx + direction * reset_data.shape[0]]], color='black', dashArray='5, 5', weight=1.5) for direction in range(4) for idx, quake in reset_data.iterrows() ] return dl.LayerGroup(id='location-uncertainties', children=uncertainties)
def make_line(row): """ Draws a line from row, a row returned by stream_route """ points, angle_deg, key, obstruct = row if abs(angle_deg) < 4: angleclass=0 elif abs(angle_deg) < 8: angleclass=1 elif abs(angle_deg) < 12: angleclass=2 elif abs(angle_deg) < 16: angleclass=3 else: angleclass=4 points = [[point[1], point[0]] for point in points] # 'key == 1' precisely if the segment is a crosswalk # note that crosswalks are never obstructed (for now!) if key == 1: color = 'yellow' elif obstruct == 1: color = 'red' else: color = ANGLE_COLOR_MAP[angleclass] return dl.Polyline(positions=points, color=color, weight= 4)
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), ]
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', dashArray='3', fillOpacity=0.1))) # Create: spatial file based on river geojson grid_rivers = dl.Polyline(positions=coords_list, weight=1, fillColor='blue', fillOpacity=0.7) # Create app app = dash.Dash(prevent_initial_callbacks=True) # Define the layout of the app # App design partly done by using 'style' function within the HTML-elements # However, css file named layout_app.css handles the more intricate styling options app.layout = html.Div([ # title: html.H1('GloFAS station selection tool'), html.Div([ # Upper row w/ headers of the different elements html.Div(html.H3('Number of steps'), style={ 'width': '29%',
def render_map(show_labels): show_labels = 'show-all-labels' in show_labels simplify = False nodes = [] links = [] lats = [] lons = [] tt_paths = {} for i, (abbr, full_name) in enumerate(BASINS.items()): oa_network_path = '../openagua_schematics/{} River.json'.format( full_name) if not os.path.exists(oa_network_path): continue with open(oa_network_path) as f: oa_network = json.load(f) pywr_model_path = '../{}/temp/pywr_model_Livneh_simplified.json'.format( full_name.replace(' ', '_').lower()) if not os.path.exists(pywr_model_path): continue with open(pywr_model_path) as f: pywr_network = json.load(f) net = oa_network['network'] tmpl = oa_network['template'] node_lookup = {n['name']: n for n in net['nodes']} if i == 0: for tt in tmpl['templatetypes']: tt_name = tt['name'] tt_svg = tt['layout'].get('svg') if not tt_svg: continue tt_path = './icons/{}.svg'.format(tt_name.replace(' ', '_')) with open(os.path.join('./assets', tt_path), 'w') as f: f.write(tt_svg) tt_paths[tt['name']] = tt_path if simplify: for n in pywr_network['nodes']: if n['name'] not in node_lookup: continue node = node_lookup[n['name']] lat, lon = float(node['y']), float(node['x']) lats.append(lat) lons.append(lon) nodes.append(leaflet.Marker(position=[lat, lon])) for n1, n2 in pywr_network['edges']: if n1 not in node_lookup or n2 not in node_lookup: continue node1 = node_lookup[n1] node2 = node_lookup[n2] lat1, lon1 = float(node1['y']), float(node1['x']) lat2, lon2 = float(node2['y']), float(node2['x']) positions = [[lat1, lon1], [lat2, lon2]] links.append(leaflet.Polyline(positions=positions)) else: for node in net['nodes']: lat, lon = float(node['y']), float(node['x']) tt = [ t for t in node['types'] if t['template_id'] == tmpl['id'] ][-1] tt_path = tt_paths.get(tt['name']) kwargs = {} if tt_path: if tt['name'].lower( ) == 'junction' or 'gauge' in tt['name'].lower(): size = 12 else: size = 24 kwargs.update(icon=dict(iconUrl=app.get_asset_url(tt_path), iconSize=[size, size], iconAnchor=[size / 2, size / 2])) nodes.append(leaflet.Marker(position=[lat, lon], **kwargs)) lats.append(lat) lons.append(lon) for link in net['links']: coords = link['layout']['geojson']['geometry']['coordinates'] lons_, lats_ = zip(*coords) positions = list(zip(*[lats_, lons_])) tt = [ t for t in link['types'] if t['template_id'] == tmpl['id'] ][-1] linestyle = tt['layout'].get('linestyle') if type(linestyle) == str: try: linestyle = json.loads(linestyle) except: linestyle = {} links.append(leaflet.Polyline(positions=positions, **linestyle)) clat = (min(lats) + max(lats)) / 2 clon = (min(lons) + max(lons)) / 2 return [ leaflet.Map( style={ 'width': '100%', 'height': '100%' }, center=[clat, clon], zoom=9, children=[ leaflet.TileLayer( url="https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"), leaflet.LayerGroup(children=nodes + links) ]) ]
def marker_click(*args): a = np.asarray(args) np.savetxt("./output.csv", a, delimiter=',') return [dl.Polyline(positions=args)]
def update_polyline(b): polyline = dl.Polyline(positions=locations) return polyline
def run(): # defining the number of steps n = 500 #creating two array for containing x and y coordinate #of size equals to the number of size and filled up with 0's x = numpy.zeros(n) y = numpy.zeros(n) global locations locations = [] #used in map generator locations_base = [] #the base data. start_location = [40.4259, -86.9081] at_risk = numpy.random.uniform(low=0.0, high=1.1, size=(n, )) start_time = 0 map_dir = "index.html" MINUTES_IN_DAY = 1440 start_date = datetime.datetime.now() times = list(range(0, n)) time_index = 0 datetimes = [] for i in range(len(times)): noise = random.randint(1, 5) times[i] = (times[i] + noise) datetimes.append(start_date + timedelta(minutes=times[i])) datetimeindex = pd.Series(range(0, n), index=datetimes) #filling the coordinates with random variables for i in range(1, n): val = random.randint(1, 4) if val == 1: x[i] = x[i - 1] + 0.001 y[i] = y[i - 1] elif val == 2: x[i] = x[i - 1] - 0.001 y[i] = y[i - 1] elif val == 3: x[i] = x[i - 1] y[i] = y[i - 1] + 0.001 else: x[i] = x[i - 1] y[i] = y[i - 1] - 0.001 locations_base.append( [x[i] + start_location[0], y[i] + start_location[1]]) ns = Namespace("dlx", "scatter") new_markers = [ dl.Marker(dl.Tooltip(f"({pos[0]}, {pos[1]}), time:{times[i]}"), position=pos, id="marker{}".format(i)) for i, pos in enumerate(locations) ] cluster = dl.MarkerClusterGroup( id="new_markers", children=new_markers, options={"polygonOptions": { "color": "red" }}) patterns = [dict(offset='0%', repeat='0', marker={})] polyline = dl.Polyline(positions=[locations], id="id_polyline") marker_pattern = dl.PolylineDecorator(id="id_marker_pattern", children=polyline, patterns=patterns) app = dash.Dash(external_scripts=[ "https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js" ]) app.layout = html.Div( html.Div([ dl.Map([ dl.TileLayer(), cluster, marker_pattern, dl.LayerGroup(id="layer") ], id="map", center=(40.4259, -86.9081), zoom=8, style={'height': '100vh'}), #html.Div(id='live-update-text'), dcc.Interval( id="interval", interval=1 * 1000, # in milliseconds n_intervals=0) ])) @app.callback(Output('id_marker_pattern', 'children'), [Input('interval', 'n_intervals')]) def update_polyline(b): polyline = dl.Polyline(positions=locations) return polyline @app.callback(Output('new_markers', 'children'), [Input('interval', 'n_intervals')]) def update_metrics(a): locations.append([locations_base[a][0], locations_base[a][1]]) if (len(locations) >= 100): locations.pop(0) new_markers = [ dl.Marker(dl.Tooltip(f"({pos[0]}, {pos[1]}), time:{times[i]}"), position=pos, id="marker{}".format(i)) for i, pos in enumerate(locations) ] return new_markers def rgb_to_hex(rgb): return ('%02x%02x%02x' % rgb) def get_time_interval(sd, ed): indices = datetimeindex[sd:ed].to_numpy() print(indices) def change_color_to_time(): for i in range(len(locations)): time = times[i] r = 255 - math.trunc(255 * (time / MINUTES_IN_DAY)) color_tuple = (r, r, r) rgb = rgb_to_hex(color_tuple) icon = { "iconUrl": f"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|{rgb}&chf=a,s,ee00FFFF", "iconSize": [20, 30], # size of the icon } markers[i].icon = icon def change_color_to_risk(): for i in range(len(locations)): time = times[i] risk = math.trunc(at_risk[i]) if (risk == 1): icon = { "iconUrl": "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FF0000&chf=a,s,ee00FFFF", "iconSize": [20, 30], # size of the icon } else: icon = { "iconUrl": "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00FF00&chf=a,s,ee00FFFF", "iconSize": [20, 30], # size of the icon } markers[i].icon = icon print("risk") def clamp(n, minn, maxn): return max(min(maxn, n), minn) def change_color_to_speed(): speed = 0 avewalk = 0.084 speeddiff = 0 for i in range(len(locations)): if i == 0: speed = 0 elif (times[i] - times[i - 1]) == 0: speed = 0 else: #coords_1 = [locations[i][0], locations[i][1]] #coords_2 = [locations[i-1][0], locations[i-1][1]] #distance = h3.point_dist(coords_1,coords_2) R = 6373.0 lat1 = radians(locations[i][0]) lon1 = radians(locations[i][1]) lat2 = radians(locations[i - 1][0]) lon2 = radians(locations[i - 1][1]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = 2 ##sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 ##2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c speed = abs(distance / (times[i] - times[i - 1])) speeddiff = speed * 1000 / 60 - 1.4 r = clamp(100 + speeddiff * 300, 0, 255) #grey normal, yellow fast, blue slow g = clamp(100 + speeddiff * 100, 0, 255) b = clamp(100 - speeddiff * 100, 0, 255) color_tuple = (int(r), int(g), int(b)) rgb = rgb_to_hex(color_tuple) icon = { "iconUrl": f"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|{rgb}&chf=a,s,ee00FFFF", "iconSize": [20, 30], # size of the icon } markers[i].icon = icon app.run_server(port=8050)