def plot(feature, mp=None, style_function=None, **map_kwargs): """Plots a GeoVector in an ipyleaflet map. Parameters ---------- feature : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection Data to plot. mp : ipyleaflet.Map, optional Map in which to plot, default to None (creates a new one). style_function : func Function that returns an style dictionary for map_kwargs : kwargs, optional Extra parameters to send to ipyleaflet.Map. """ map_kwargs.setdefault('basemap', basemaps.Stamen.Terrain) if feature.is_empty: warnings.warn("The geometry is empty.") mp = Map(**map_kwargs) if mp is None else mp else: if mp is None: center = feature.envelope.centroid.reproject(WGS84_CRS) zoom = zoom_level_from_geometry(feature.envelope) mp = Map(center=(center.y, center.x), zoom=zoom, **map_kwargs) mp.add_layer(layer_from_element(feature, style_function)) return mp
def visualize_sequence_on_map(self, sequence: list): """ Visualizes the resulting sequence of cities on a open source map. :param sequence: list [int] :return: """ self.sequence = sequence # Get Marker positions and create map with markers: markers = self._create_markers(sequence) m = Map(center=markers[0].location, zoom=7, scroll_wheel_zoom=True) marker_cluster = MarkerCluster(markers=markers) m.add_layer(marker_cluster) # Create line between cities: line = Polyline(locations=[x.location for x in markers], color="red", fill=False) m.add_layer(line) m.layout.width = '100vw' m.layout.height = '100vh' # Save file and show in webbrowser: fname = "utils/tmp/map.html" realpath = os.path.realpath(fname) m.save(fname) # webbrowser.open_new_tab(fname) webbrowser.open_new_tab("file://" + realpath) print( "...Opening interactive streetmap in browser. If browser does not show the map correctly, try opening " "the saved HTML-file ({n}) manually.".format(n=realpath))
def ipyleaflet_scatterplot_per_class( x, y, center=(0, 0), zoom=5, proportion=1.0, colors=['blue', 'red', 'yellow', 'orange'], m=None, width='600px', height='400px'): if m is None: m = Map(center=center, zoom=zoom) m.layout.width = width m.layout.height = height if proportion < 1.0: n_samples = int(x.shape[0] * proportion) x, y = shuffle(x, y) x = x[:n_samples] y = y[:n_samples] for sample_x, sample_y in zip(x.tolist(), y.tolist()): circle = Circle() circle.location = sample_x circle.radius = 100 circle.color = colors[sample_y] circle.fill_color = colors[sample_y] m.add_layer(circle) return m
def print_geojson(geojson, limit=100): center = None j = json.load(StringIO(geojson)) layer_group = LayerGroup() features = j['features'] if limit is not None: features = features[0:limit] for f in features: location = (f['geometry']['coordinates'][1], f['geometry']['coordinates'][0]) marker = Marker(location=location) marker.popup = HTML(str(f['properties'])) layer_group.add_layer(marker) if not center: center = location if not center: center = (0, 0) m = Map(layers=(basemap_to_tiles(basemaps.OpenStreetMap.Mapnik), ), center=center, zoom=8) m.add_layer(layer_group) return m
def draw_interactive_map(): """ Draws interactive map to be able to draw/define a region of interest """ wms_drillholes = WMSLayer( url='http://geo.loop-gis.org/geoserver/loop/wms?', layers='loop:collar_4326', format='image/png', transparent=True, attribution='Drilhole collar from GSWA', name='drillhole collars' ) wms_geol = WMSLayer( url='http://geo.loop-gis.org/geoserver/loop/wms?', layers='loop:2_5m_interpgeop15_4326', format='image/png', transparent=True, opacity=0.4, attribution='Geology data from GSWA', name='geology' ) m =Map(basemap=basemaps.OpenTopoMap, center=(-29,116.5), zoom=8,scroll_wheel_zoom=True) m.add_layer(wms_geol) m.add_layer(wms_drillholes) m.add_control(LayersControl()) dc = DrawControl(rectangle={'shapeOptions': {'color': '#0000FF'}}) m.add_control(dc) m
def drawPOIS(POIS, zoom=12): centerLat, centerLog = 0, 0 # taking the average of all latitude and longitude of all the POIs # to get the center of the map for poi in POIS: centerLat += poi.coordinates[0] centerLog += poi.coordinates[1] centerLat /= len(POIS) centerLog /= len(POIS) center = (centerLog, centerLat) m = Map(center=center, zoom=zoom, close_popup_on_click=False) # creating the popup messages on the markers # with the name of the POI for poi in POIS: name = poi.address.split(",")[0] marker = Marker(location=poi.coordinates[::-1]) text = HTML() text.value = f"{name}" marker.popup = text m.add_layer(marker) return m
def plot(feature, mp=None, style_function=None, **map_kwargs): """Plots a GeoVector in an ipyleaflet map. Parameters ---------- feature : Any object with __geo_interface__ Data to plot. mp : ipyleaflet.Map, optional Map in which to plot, default to None (creates a new one). style_function : func Function that returns an style dictionary for map_kwargs : kwargs, optional Extra parameters to send to folium.Map. """ if feature.is_empty: warnings.warn("The geometry is empty.") mp = Map(basemap=basemaps.Stamen.Terrain, ** map_kwargs) if mp is None else mp else: if mp is None: center = feature.envelope.centroid.reproject(WGS84_CRS) zoom = zoom_level_from_geometry(feature.envelope) mp = Map(center=(center.y, center.x), zoom=zoom, basemap=basemaps.Stamen.Terrain, **map_kwargs) mp.add_layer(layer_from_element(feature, style_function)) return mp
def plot_gps_clusters(ds, user_id:str, zoom=5): """ Plots GPS coordinates Args: ds (DataStream): datastream object user_id (str): uuid of a user zoom: min 0 and max 100, zoom map """ pdf = ds_to_pdf(ds, user_id) marker_list = [] center = None for index, row in pdf.iterrows(): if center is None: center = [row["latitude"], row["longitude"]] marker_list.append(Marker(location=(row["latitude"], row["longitude"]))) m = Map(center=(center), zoom=zoom) marker_cluster = MarkerCluster( markers=(marker_list) ) m.add_layer(marker_cluster) return m
def show_map(selected_stats, year): control = WidgetControl(widget=districtbox, position='topright', min_width = 250, max_width=500) # load selected stats into choro_data_all choro_data_all, unit = choro_data_complete[selected_stats], units[selected_stats] # for geo plot extract chosen year and assign to choro_data choro_data = choro_data_all[choro_data_all['year']==year] choro_data = dict(choro_data.drop(columns=['year', 'name']).to_dict('split')['data']) # initialize bar chart with Frankfurt vs Offenbach update_figure('06412', selected_stats, choro_data_all, year) update_figure('06413', selected_stats, choro_data_all, year) # initialize districtbox loading_name, loading_values = id_to_name['06413'], choro_data['06413'] districtbox.value = f'<center><p><b>{loading_name}</b>:</p> {loading_values:g} {unit} {norm_unit}</center>' # set y-axis label fig.update_layout(yaxis_title=f'{stat_dict[selected_stats]} [{unit} {norm_unit}]', yaxis={'range':[0,max(choro_data_all[selected_stats])]}) # define chropleth layer for basic geo plotting layer = Choropleth(geo_data=geo_data,choro_data=choro_data,colormap=cm, style={'fillOpacity': 0.65, 'dashArray': '0, 0', 'weight':1}) # define GeoJSON layer for click and hover event interactions geo_json = GeoJSON(data=geo_data, style={'opacity': 0, 'dashArray': '9', 'fillOpacity': .0, 'weight': 1}, hover_style={'color': 'blue', 'dashArray': '0', 'fillOpacity': 0.7}) # on hover, the districtbox is updated to show properties of the hovered district def update_districtbox(feature, **kwargs): feature['value'] = choro_data[feature['id']] districtbox.value = f'<center><p><b>{id_to_name[feature["id"]]}</b>:</p> {feature["value"]:g} {unit} {norm_unit}</center>' # this function is called upon a click events and triggers figure update with the arguments passed from the map def update_fig_on_click(feature, **kwags): update_figure(feature['id'], selected_stats, choro_data_all, year) geo_json.on_hover(update_districtbox) geo_json.on_click(update_fig_on_click) # add layers and controls; set layout parameters m = Map(basemap=basemaps.OpenStreetMap.Mapnik, center=(50.5,9), zoom=8) m.add_layer(layer) m.add_layer(geo_json) m.add_control(control) m.layout.width = '40%' m.layout.height = '700px' # custom made legend using min/max normalization min_value, max_value = min(choro_data.values()), max(choro_data.values()) legend = LegendControl( {f"{min_value:g} {unit} {norm_unit}": cm(0), #hier f"{min_value+0.5*(max_value-min_value):g} {unit} {norm_unit}": cm(.5), f"{max_value:g} {unit} {norm_unit}": cm(1)}, name= f"{stat_dict[selected_stats]} ({year})", position="bottomleft") m.add_control(legend) return HBox([m, fig], layout=Layout(width='85%'))
def plotHeatmap(locations: [tuple], heatmapName: str, worldMap: lf.Map = None, center: tuple = (0, 0), **kwargs) -> lf.Map: ''' Plot the given lat lon locations as a heatmap layer on a world map object @center: the center coordinate when creating the world map object @locations: list of latitude & longitude pair @worldMap: ipyleaflet Map object. If this is specified, the new heatmap will be addded to this object. Else a new Map object will be created @heatmapName: name of the heatmap layer Returns: a newly created Map object or the passed in worldMap object. ''' # Create map if it's not passed in to the function if (worldMap is None): baseMap = lf.basemaps.CartoDB.DarkMatter # lf.basemaps.Esri.WorldTopoMap worldMap = lf.Map(basemap=baseMap, center=center, zoom=10) worldMap.add_control(lf.FullScreenControl()) worldMap.add_control(lf.LayersControl(position='topright')) # Remove existing heatmap layer that has the same name removeLayerByType(worldMap, heatmapName, lf.Heatmap) # Add the heatmap layer to the world map object heatmap = lf.Heatmap(locations=locations, radius=20, name=heatmapName, **kwargs) worldMap.add_layer(heatmap) return worldMap
def build_map(self, click_handler): mean_lat = self.x_data[self.lat_key].values.mean() mean_lng = self.x_data[self.lon_key].values.mean() # create the map m = Map(center=(mean_lat, mean_lng), zoom=4, basemap=basemaps.Stamen.Terrain) m.layout.height = '600px' # show trace markers = [] for k in self.marker_info: lat, lon = k message = HTML() message.description = "Station ID" message.value = str(self.marker_info[k]) message.placeholder = "" marker = Marker(location=(lat, lon)) marker.on_click(click_handler) marker.popup = message markers.append(marker) marker_cluster = MarkerCluster( markers=markers ) # not sure whether we could register once instead of each marker: # marker_cluster.on_click(click_handler) m.add_layer(marker_cluster) # m.add_control(FullScreenControl()) return m
class LeafletMap: def __init__(self, bounds: tuple): self.layer = None self._leaflet_map = Map(layers=(basemap_to_tiles( basemaps.OpenStreetMap.BlackAndWhite), ), name="Leaflet Map", center=center(bounds), zoom=12, scroll_wheel_zoom=True) self._leaflet_map.add_control(FullScreenControl()) @property def map(self): return self._leaflet_map def update(self, layer: Layer): self.layer = layer self._remove_layers() self._update_layers() def _remove_layers(self): for layer in self._leaflet_map.layers: if isinstance(layer, TileLayer): continue self._leaflet_map.remove_layer(layer) def _update_layers(self): if self.layer.empty: return self._leaflet_map.add_layer(self.layer.layer)
def ipyleaflet_contourmap( center, datapoints=None, contourmap=None, isolines=[0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1], lineopacity=1.0, colormap=linear.viridis, fillopacity=0.7, legend_title='Legend', m=None, zoom=11, width='600px', height='400px'): if m is None: m = Map(center=center, zoom=zoom) m.layout.width = width m.layout.height = height cs = contourmap colors = [ colormap(i / (len(cs.levels) - 1)) for i in range(len(cs.levels) - 1) ] allsegs = cs.allsegs allkinds = cs.allkinds for clev in range(len(cs.allsegs)): kinds = None if allkinds is None else allkinds[clev] segs = split_contours(allsegs[clev], kinds) polygons = Polygon( locations=[p.tolist() for p in segs], # locations=segs[14].tolist(), color=colors[clev], weight=2, opacity=lineopacity, fill_color=colors[clev], fill_opacity=fillopacity) m.add_layer(polygons) if datapoints is not None: m = ipyleaflet_scatterplot_per_class(datapoints[0], datapoints[1], proportion=1.0, m=m) legend_colors = {} for i in reversed(range(len(isolines) - 1)): legend_colors["{:0.1f}-{:0.1f}".format( isolines[i], isolines[i + 1])] = colormap(i / (len(isolines) - 1)) legend = LegendControl(legend_colors, name=legend_title, position="topright") m.add_control(legend) return m
def showonmap(self): try: from ipyleaflet import Map, Marker except ModuleNotFoundError: print('Non riesco ad importare i moduli.') poi = (self.data['Location']['Y'],self.data['Location']['X']) m = Map(center=poi, zoom=15) marker = Marker(location=poi, draggable=True) m.add_layer(marker); display(m)
def draw_map(lat_longs): center = [37.79481, -122.41186] zoom = 12 m = Map(center=center, zoom=zoom, basemap=basemaps.Hydda.Full) m.layout.height = '650px' pl = Polyline(locations=lat_longs) pl.color = path_color.value pl.fill_color = path_color.value m.add_layer(pl) return m
def flight_map_leaflet( flight: "Flight", *, zoom: int = 7, highlight: Optional[Dict[str, Union[str, Flight, Callable[[Flight], Optional[Flight]]], ]] = None, airport: Union[None, str, Airport] = None, **kwargs, ) -> Optional[Map]: from traffic.core import Flight from traffic.data import airports last_position = flight.query("latitude == latitude").at() # type: ignore if last_position is None: return None _airport = airports[airport] if isinstance(airport, str) else airport if "center" not in kwargs: if _airport is not None: kwargs["center"] = _airport.latlon else: kwargs["center"] = ( flight.data.latitude.mean(), flight.data.longitude.mean(), ) m = Map(zoom=zoom, **kwargs) if _airport is not None: m.add_layer(_airport) elt = m.add_layer(flight) elt.popup = HTML() elt.popup.value = flight._info_html() if highlight is None: highlight = dict() for color, value in highlight.items(): if isinstance(value, str): value = getattr(Flight, value, None) if value is None: continue assert not isinstance(value, str) f: Optional[Flight] if isinstance(value, Flight): f = value else: f = value(flight) if f is not None: m.add_layer(f, color=color) return m
def Location(self): # Import pra tratamento das coordenadas self.results = geocoder.geocode(u'Brussels, Belgium') self.center = (self.results[0]['geometry']['lat'], self.results[0]['geometry']['lng']) map = Map(center=self.center, zoom=6) self.marker = Marker(location=self.center, draggable=False) map.add_layer(self.marker) map
def map_shapefile(gdf, colormap=mpl.cm.YlOrRd, weight=2, default_zoom=13): def n_colors(n, colormap=colormap): data = np.linspace(0.0, 1.0, n) c = [mpl.colors.rgb2hex(d[0:3]) for d in colormap(data)] return c def data_to_colors(data, colormap=colormap): c = [ mpl.colors.rgb2hex(d[0:3]) for d in colormap(mpl.colors.Normalize()(data)) ] return c def click_handler(event=None, id=None, properties=None, type=None, coordinates=None): try: datasetID = properties['time'] print(datasetID) except: pass # Convert to WGS 84 and geojson format gdf_wgs84 = gdf.to_crs(epsg=4326) data = gdf_wgs84.__geo_interface__ # For each feature in dataset, append colour values n_features = len(data['features']) colors = n_colors(n_features) for feature, color in zip(data['features'], colors): feature['properties']['style'] = { 'color': color, 'weight': weight, 'fillColor': color, 'fillOpacity': 1.0 } # Get centroid to focus map on lon, lat = gdf_wgs84.unary_union.centroid.coords.xy # Plot map and add geojson layers m = Map(center=(lat[0], lon[0]), zoom=default_zoom, basemap=basemaps.Esri.WorldImagery, layout=dict(width='800px', height='600px')) feature_layer = GeoJSON(data=data) feature_layer.on_click(click_handler) m.add_layer(feature_layer) return m
class openeoMap: def __init__(self, center, zoom): self.map = Map(center=center, zoom=zoom, scroll_wheel_zoom=True, interpolation='nearest') self.bbox = [] self.point_coords = [] self.figure = None self.figure_widget = None feature_collection = {'type': 'FeatureCollection', 'features': []} draw = DrawControl( circlemarker={}, polyline={}, polygon={}, marker={"shapeOptions": { "original": {}, "editing": {}, }}, rectangle={"shapeOptions": { "original": {}, "editing": {}, }}) self.map.add_control(draw) def handle_draw(target, action, geo_json): feature_collection['features'] = [] feature_collection['features'].append(geo_json) if feature_collection['features'][0]['geometry'][ 'type'] == 'Point': self.point_coords = feature_collection['features'][0][ 'geometry']['coordinates'] else: coords = feature_collection['features'][0]['geometry'][ 'coordinates'][0] polygon = shapely.geometry.Polygon(coords) self.bbox = polygon.bounds layers_control = LayersControl(position='topright') self.map.add_control(layers_control) self.map.add_control(FullScreenControl()) self.map.add_layer(basemap_to_tiles(basemaps.Esri.WorldImagery)) draw.on_draw(handle_draw) def getBbox(self): if (len(self.bbox) == 0): mapBox = self.map.bounds return [mapBox[0][1], mapBox[0][0], mapBox[1][1], mapBox[1][0]] else: return self.bbox
def display_da(da, cm): """ Description: Display a colored xarray.DataArray on a map and allow the user to select a point ----- Input: da: xarray.DataArray cm: matplotlib colormap Output: m: map to interact with dc: draw control Usage: View, interact and point a location to be used later on """ # Check inputs assert 'dataarray.DataArray' in str( type(da)), "da must be an xarray.DataArray" # convert DataArray to png64 imgurl = da_to_png64(da, cm) # Display latitude = (da.latitude.values.min(), da.latitude.values.max()) longitude = (da.longitude.values.min(), da.longitude.values.max()) margin = -0.5 zoom_bias = 0 lat_zoom_level = _degree_to_zoom_level(margin=margin, * latitude) + zoom_bias lon_zoom_level = _degree_to_zoom_level(margin=margin, * longitude) + zoom_bias zoom = min(lat_zoom_level, lon_zoom_level) - 1 center = [np.mean(latitude), np.mean(longitude)] m = Map(center=center, zoom=zoom) # http://leaflet-extras.github.io/leaflet-providers/preview/ esri = basemap_to_tiles(basemaps.Esri.WorldImagery) m.add_layer(esri) io = ImageOverlay(name='DataArray', url=imgurl, bounds=[(latitude[0], longitude[0]), (latitude[1], longitude[1])]) m.add_layer(io) dc = DrawControl(circlemarker={'color': 'yellow'}, polygon={}, polyline={}) m.add_control(dc) m.add_control(LayersControl()) return m, dc, io
def bdc_plot_datasets(datasets, zoom=4, layout=Layout(width='600px', height='600px')): """Plot Dataset tiles """ bbox = get_bounds(datasets, datasets[0].crs) bbox_pol = shapely.wkt.loads(bbox.wkt) project = partial(pyproj.transform, pyproj.Proj(datasets[0].crs.crs_str), pyproj.Proj(init='epsg:4674')) bbox_pol_wgs84 = transform(project, bbox_pol) bbox = bbox_pol_wgs84.bounds center = ((bbox[1] + bbox[3]) / 2, (bbox[0] + bbox[2]) / 2) m = Map(basemap=basemaps.Esri.WorldImagery, center=center, zoom=zoom, layout=layout) grid = WMSLayer( url='http://brazildatacube.dpi.inpe.br/bdc/geoserver/grids/ows', layers='BDC_GRID', styles='tiles', format='image/png', transparent=True, tile_size=512) m.add_layer(grid) if len(datasets): project = partial(pyproj.transform, pyproj.Proj(datasets[0].crs.crs_str), pyproj.Proj(init='epsg:4674')) plotted = [] for ds in datasets: idt = "{},{};{},{}".format(ds.metadata.lon[0], ds.metadata.lat[0], ds.metadata.lon[1], ds.metadata.lat[1]) if idt not in plotted: plotted.append(idt) # apply projection ds_pol = transform(project, shapely.wkt.loads(ds.extent.wkt)) x, y = ds_pol.exterior.xy points = [(y1, x1) for x1, y1 in zip(x, y)] polygon = Polygon(locations=points, color="#0033CC", fill_color="#388b8b", weight=2, fill_opacity=.6) m.add_layer(polygon) return m
def plot(self, mask=None, segment_ids=None, zoom=12): """Plot ride segments on map in Jupyter Notebook :params mask: list of booleans to select which segments of the ride to map :params segment_ids: index or list of segment ids to select which segments of the ride to map :params zoom: initial zoom level """ if mask and segment_ids: raise Exception('Pass either a mask or a list of ids, not both') segments = self.segments if mask: segments = [sgm for i, sgm in enumerate(segments) if mask[i]] elif segment_ids: if not isinstance(segment_ids, list): segment_ids = [segment_ids] segments = [sgm for sgm in segments if sgm['id'] in segment_ids] lats_start = [sgm['lat_start'] for sgm in segments] lons_start = [sgm['lon_start'] for sgm in segments] lats_end = [sgm['lat_end'] for sgm in segments] lons_end = [sgm['lon_end'] for sgm in segments] median_lat = np.median(lats_start + lats_end) median_lon = np.median(lons_start + lons_end) map = Map(center=(median_lat, median_lon), zoom=zoom) if mask or segment_ids: for sgm in segments: position_start = (sgm['lat_start'], sgm['lon_start']) position_end = (sgm['lat_end'], sgm['lon_end']) poly_line = Polyline( locations=(position_start, position_end), color="red", fill=False, weight=3 ) map.add_layer(poly_line) else: positions = [ (sgm['lat_start'], sgm['lon_start']) for sgm in segments ] positions.append((segments[-1]['lat_end'], segments[-1]['lon_end'])) poly_line = Polyline( locations=positions, color="red", fill=False, weight=3 ) map.add_layer(poly_line) return map
def rasters_on_map(rasters_list, out_dir, overlay_names_list, geojson_data=None): """ displays a raster on a ipyleaflet map :param rasters_list: rasters to display (rasterio image) :param out_dir: path to the output directory (preview writing) :param overlay_names_list: name of the overlays for the map """ # - get bounding box raster = rasters_list[0] epsg4326 = {'init': 'EPSG:4326'} bounds = transform_bounds(raster.crs, epsg4326, *raster.bounds) center = [(bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2] # - get centered map m = Map(center=(center[-1], center[0]), zoom=10) # - plot quicklook for raster, overlay_name in zip(rasters_list, overlay_names_list): bounds = transform_bounds(raster.crs, epsg4326, *raster.bounds) quicklook_url = os.path.join( out_dir, "PREVIEW_{}.JPG".format(datetime.datetime.now())) write_quicklook(raster, quicklook_url) quicklook = ImageOverlay(url=quicklook_url, bounds=((bounds[1], bounds[0]), (bounds[3], bounds[2])), name=overlay_name) m.add_layer(quicklook) m.add_control(LayersControl()) m.add_control(FullScreenControl()) # - add geojson data if geojson_data is not None: geo_json = GeoJSON(data=geojson_data, style={ 'color': 'green', 'opacity': 1, 'weight': 1.9, 'dashArray': '9', 'fillOpacity': 0.1 }) m.add_layer(geo_json) # - add draw control dc = DrawControl() m.add_control(dc) return m, dc
def show_stations_on_map(self,list_inc,list_process,list_filters, opt_params): """ Returns an interactive map of source and stations, use only in Jupyter Notebooks. Inputs: | list_inc: list of incidents | list_process: list of processes, one list per incident | list filters: list of filters defined for stations | opt_params: optional parameters (dictionary) Optional parameters: """ records = self._extract_records(list_inc, list_process, list_filters) if not records: LOGGER.warning("There are no records to satisfy the provided" " filters.") return m = Map( basemap=basemap_to_tiles(basemaps.Esri.WorldImagery, "2020-04-08"), center = (Station.pr_source_loc[0],Station.pr_source_loc[1]), zoom = 8, close_popup_on_click=True ) for i in records: if not i[0]: continue lat = i[0].station.lat lon = i[0].station.lon marker = Marker(location=(lat, lon), draggable=False, icon=AwesomeIcon(name="map-pin", marker_color='green', icon_color='darkgreen'), opacity=0.8) m.add_layer(marker) message = HTML() message.value = i[0].station.inc_st_name[list_inc[0]] marker.popup = message m.add_layer(Marker(icon=AwesomeIcon(name="star", marker_color='red', icon_color='darkred'), location=(Station.pr_source_loc[0],Station.pr_source_loc[1]), draggable=False)) return m
def flight_map(self, center=None, basemap=None, zoom=8): """Display interactive map of the flight path. (Jupyter notebook only.) Parameters ---------- center: tuple, optional (latitude, longitude) center of the map. The default is the average of the flight's lat/lon bounding box. basemap: str, or list or tuple of str, optional Name of the base map available in ipyleaflet. Default: ``('Esri.WorldImagery', 'OpenTopoMap')``. zoom: int, optional Map zoom level. Default is 8. """ if not display_map: raise RuntimeError('Cannot display map') if basemap is None: basemap = ('Esri.WorldImagery', 'OpenTopoMap') elif isinstance(basemap, str): basemap = (basemap, ) elif not isinstance(basemap, (list, tuple)): raise TypeError('basemap is not a str, list, or tuple') base_layers = list() for layer in basemap: name_parts = layer.split('.') base_layer = basemaps for p in name_parts: base_layer = base_layer[p] if not isinstance(base_layer, dict): raise TypeError('base layer not a dict') base_layers.append(basemap_to_tiles(base_layer)) data = self._flight flight_lat = data['latitude'] flight_lon = data['longitude'] if center is None: center = (flight_lat.mean(), flight_lon.mean()) flight_path = Polyline( locations=[np.column_stack((flight_lat, flight_lon)).tolist()], color='blue', fill=False, name='Flight path') flight_map = Map(center=center, zoom=int(zoom)) for _ in base_layers: flight_map.add_layer(_) flight_map.add_layer(flight_path) flight_map.add_control(FullScreenControl()) flight_map.add_control(LayersControl()) display(flight_map)
def create_map(normalized_image: np.ndarray) -> Map: """ Creates leaflet map with given image :param normalized_image: Image data normalized to 0-255 8-bit integer :return: Leaflet map """ width = normalized_image.shape[0] height = normalized_image.shape[1] bounds = [(-width / 2, -height / 2), (width / 2, height / 2)] layer = ImageOverlay(url=serialize_to_url(normalized_image), bounds=bounds) leaflet = Map(center=[0, 0], zoom=1, interpolation='nearest') leaflet.clear_layers() leaflet.add_layer(layer) return leaflet
def make_map(X_test): m = Map(center=(-6, 35), zoom=5, scroll_wheel_zoom=True) def create_marker(row): lat_lon = (row["latitude"], row["longitude"]) return CircleMarker(location=lat_lon, draggable=False, fill_color="#055a8c", fill_opacity=0.35, radius=1, stroke=False) markers = X_test.apply(create_marker, axis=1) layer_group = LayerGroup(layers=tuple(markers.values)) m.add_layer(layer_group) return m
def plot_locations(alamat): # location address location = geocoder.osm(alamat) # latitude and longitude of location latlng = [location.lat, location.lng] # create map plot_locations_map = Map(center=latlng, zoom=16) # marker marker = Marker(location=latlng, title=str(alamat)) plot_locations_map.add_layer(marker) # display map display(plot_locations_map)
def draw_heat_map(center, df, radius = 16): """ Takes in the center as a tuple and returns a heat map of the life lines in the given area.""" from ipyleaflet import Map,Marker,CircleMarker,Heatmap from ipywidgets import HTML from ipyleaflet import Popup m = Map(center = center, zoom = 11) heatmap = Heatmap( locations=[(df.loc[i, "lat"], df.loc[i,"lng"]) for i in df.index], radius= radius ) m.add_layer(heatmap); return display(m)
def wrapper(*args, **kwargs): legend_file = BytesIO() value = func(*args, **kwargs) overwrite_parameters(other_options, kwargs) overwrite_parameters(plot_options, kwargs) if isinstance(value, xr.Dataset): if "varin" not in kwargs_dec: print("Error") geojson_str = return_geojson(value[kwargs_dec.get("varin")], plot_options, legend_file, **other_options) name = kwargs_dec.get("varin") else: name = value.name geojson_str = return_geojson(value, plot_options, legend_file, **other_options) geojson_data = json.loads(geojson_str) apply_style(geojson_data["features"]) #if "country_file" in kwargs_dec: # crop_country(geojson_data,country_file=kwargs_dec.get("country_file")) geojson_layer = GeoJSON(data=geojson_data, name=name) map_out = Map(zoom=6, center=(float(value.latitude.mean().values), float(value.longitude.mean().values))) map_out.add_layer(geojson_layer) if kwargs_dec.get("borders", False): if "country_file" in kwargs_dec: bord = Borders(fname=kwargs_dec.get("country_file"), color="black") map_out.add_layer(bord) if plot_options["save_colorbar"]: legend_file.seek(0) legend = widgets.Image(layout=widgets.Layout(height="430px")) legend.value = legend_file.read() widg_out = widgets.HBox([map_out, legend]) else: widg_out = map_out return widg_out