def map_results_raster(structure_list, raster, breach=None, book=None, width=800, height=700, zoom = 14):
    from folium import raster_layers
    colormap=lambda x: (0, 0, 0, x)
    
    overtopped={}
    # Read in Raster Data
    src = gdal.Open(raster)
    ulx, xres, xskew, uly, yskew, yres  = src.GetGeoTransform()
    lrx = ulx + (src.RasterXSize * xres)
    lry = uly + (src.RasterYSize * yres)
    centerx, centery  = np.mean([ulx, lrx]),np.mean([uly, lry])
    img = src.ReadAsArray()
        
    colormap=lambda x: (0, 1, 1, x)
    folmap = Map(width=800, height=700, location=[centery, centerx], zoom_start=zoom)
    folmap.add_child(raster_layers.ImageOverlay(img, colormap=colormap,opacity=0.5, bounds =[[lry, lrx],[uly, ulx]], mercator_project=True))
    
    if isinstance(breach, gpd.geodataframe.GeoDataFrame):
        if breach.crs != '4326':
            breach = breach.to_crs({'init' :'epsg:4326'})
        html = f"""<h4>Breach Location</h4>"""    
        iframe=branca.element.IFrame(html=html, width=120, height=80)    
        popup = folium.Popup(iframe)  
        folmap.add_child(folium.CircleMarker(location=[breach.loc[0, 'geometry'].y, 
                                     breach.loc[0, 'geometry'].x], 
                                     popup= popup,radius=6, weight=12, color='Red'))
        
    if isinstance(book, gpd.geodataframe.GeoDataFrame):
        print('Book!', book.crs)
        if book.crs != {'init': 'epsg:4326'}:
            print('Projecting')
            book = book.to_crs({'init' :'epsg:4326'})
            # Placeholder for plotting structures
            

    for structures in structure_list:
        #print(structures.crs)
        if structures.crs != '4326':
            structures = structures.to_crs({'init' :'epsg:4326'})
        try:


            for idx in structures.index:
                sID =  structures.loc[idx, 'ID']  
                sWSE = round(structures.loc[idx, 'Max WSE'],2)
                sCrest = round(structures.loc[idx, 'Crest'],2)
                sStation = int(structures.loc[idx, 'Station'])

                if sWSE < sCrest:
                    html = f"""<h4>{sID}</h4><p>Station {sStation}</p><p>Levee Crest {sCrest}</p><p>Max WSE {sWSE}</p>"""
                    iframe=branca.element.IFrame(html=html, width=200, height=150)    
                    popup = folium.Popup(iframe)  
                    folmap.add_child(folium.CircleMarker(location=[structures.loc[idx, 'geometry'].y, 
                                                 structures.loc[idx, 'geometry'].x], 
                                                 popup= popup,radius=3, weight=3, color='black'))
                else:
                    max_depth=round(sWSE-sCrest,2)
                    overtopped[f'{sID} Station {sStation}'] =  max_depth
                    html = f"""<h4>{sID}</h4><p>Station {sStation}</p><p>Levee Crest {sCrest}</p><p>Max WSE {sWSE}</p><p>Max Overtopping Depth {max_depth}</p>"""
                    iframe=branca.element.IFrame(html=html, width=200, height=250)    
                    popup = folium.Popup(iframe) 
                    folmap.add_child(folium.CircleMarker(location=[structures.loc[idx, 'geometry'].y, 
                                                 structures.loc[idx, 'geometry'].x], 
                                                 popup= popup,radius=4, weight=4, color='red'))
                    
            line_points = zip(structures.geometry.y.values,structures.geometry.x.values)
            folium.PolyLine(list(line_points), color='black').add_to(folmap)
        except:
            print('ERROR')
                
    add_tiles(folmap)
    return folmap, overtopped
Ejemplo n.º 2
0
class DualMap(MacroElement):
    """Create two maps in the same window.

    Adding children to this objects adds them to both maps. You can access
    the individual maps with `DualMap.m1` and `DualMap.m2`.

    Uses the Leaflet plugin Sync: https://github.com/jieter/Leaflet.Sync

    Parameters
    ----------
    location: tuple or list, optional
        Latitude and longitude of center point of the maps.
    layout : {'horizontal', 'vertical'}
        Select how the two maps should be positioned. Either horizontal (left
        and right) or vertical (top and bottom).
    **kwargs
        Keyword arguments are passed to the two Map objects.

    Examples
    --------
    >>> # DualMap accepts the same arguments as Map:
    >>> m = DualMap(location=(0, 0), tiles='cartodbpositron', zoom_start=5)
    >>> # Add the same marker to both maps:
    >>> Marker((0, 0)).add_to(m)
    >>> # The individual maps are attributes called `m1` and `m2`:
    >>> Marker((0, 1)).add_to(m.m1)
    >>> LayerControl().add_to(m)
    >>> m.save('map.html')

    """

    _template = Template("""
        {% macro script(this, kwargs) %}
            {{ this.m1.get_name() }}.sync({{ this.m2.get_name() }});
            {{ this.m2.get_name() }}.sync({{ this.m1.get_name() }});
        {% endmacro %}
    """)

    def __init__(self, location=None, layout='horizontal', **kwargs):
        super(DualMap, self).__init__()
        for key in ('width', 'height', 'left', 'top', 'position'):
            assert key not in kwargs, ('Argument {} cannot be used with '
                                       'DualMap.'.format(key))
        if layout not in ('horizontal', 'vertical'):
            raise ValueError(
                'Undefined option for argument `layout`: {}. '
                'Use either \'horizontal\' or \'vertical\'.'.format(layout))
        width = '50%' if layout == 'horizontal' else '100%'
        height = '100%' if layout == 'horizontal' else '50%'
        self.m1 = Map(location=location,
                      width=width,
                      height=height,
                      left='0%',
                      top='0%',
                      position='absolute',
                      **kwargs)
        self.m2 = Map(location=location,
                      width=width,
                      height=height,
                      left='50%' if layout == 'horizontal' else '0%',
                      top='0%' if layout == 'horizontal' else '50%',
                      position='absolute',
                      **kwargs)
        figure = Figure()
        figure.add_child(self.m1)
        figure.add_child(self.m2)
        # Important: add self to Figure last.
        figure.add_child(self)
        self.children_for_m2 = []
        self.children_for_m2_copied = []  # list with ids

    def _repr_html_(self, **kwargs):
        """Displays the HTML Map in a Jupyter notebook."""
        if self._parent is None:
            self.add_to(Figure())
            out = self._parent._repr_html_(**kwargs)
            self._parent = None
        else:
            out = self._parent._repr_html_(**kwargs)
        return out

    def add_child(self, child, name=None, index=None):
        """Add object `child` to the first map and store it for the second."""
        self.m1.add_child(child, name, index)
        if index is None:
            index = len(self.m2._children)
        self.children_for_m2.append((child, name, index))

    def render(self, **kwargs):
        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        # Import Javascripts
        for name, url in _default_js:
            figure.header.add_child(JavascriptLink(url), name=name)

        super(DualMap, self).render(**kwargs)

        for child, name, index in self.children_for_m2:
            if child._id in self.children_for_m2_copied:
                # This map has been rendered before, child was copied already.
                continue
            child_copy = deep_copy(child)
            if isinstance(child_copy, LayerControl):
                child_copy.reset()
            self.m2.add_child(child_copy, name, index)
            # m2 has already been rendered, so render the child here:
            child_copy.render()
            self.children_for_m2_copied.append(child._id)

    def fit_bounds(self, *args, **kwargs):
        for m in (self.m1, self.m2):
            m.fit_bounds(*args, **kwargs)

    def keep_in_front(self, *args):
        for m in (self.m1, self.m2):
            m.keep_in_front(*args)
Ejemplo n.º 3
0
class DualMap(MacroElement):
    """Create two maps in the same window.

    Adding children to this objects adds them to both maps. You can access
    the individual maps with `DualMap.m1` and `DualMap.m2`.

    Uses the Leaflet plugin Sync: https://github.com/jieter/Leaflet.Sync

    Parameters
    ----------
    location: tuple or list, optional
        Latitude and longitude of center point of the maps.
    layout : {'horizontal', 'vertical'}
        Select how the two maps should be positioned. Either horizontal (left
        and right) or vertical (top and bottom).
    **kwargs
        Keyword arguments are passed to the two Map objects.

    Examples
    --------
    >>> # DualMap accepts the same arguments as Map:
    >>> m = DualMap(location=(0, 0), tiles='cartodbpositron', zoom_start=5)
    >>> # Add the same marker to both maps:
    >>> Marker((0, 0)).add_to(m)
    >>> # The individual maps are attributes called `m1` and `m2`:
    >>> Marker((0, 1)).add_to(m.m1)
    >>> LayerControl().add_to(m)
    >>> m.save('map.html')

    """

    _template = Template("""
        {% macro script(this, kwargs) %}
            {{ this.m1.get_name() }}.sync({{ this.m2.get_name() }});
            {{ this.m2.get_name() }}.sync({{ this.m1.get_name() }});
        {% endmacro %}
    """)

    def __init__(self, location=None, layout='horizontal', **kwargs):
        super(DualMap, self).__init__()
        for key in ('width', 'height', 'left', 'top', 'position'):
            assert key not in kwargs, ('Argument {} cannot be used with '
                                       'DualMap.'.format(key))
        if layout not in ('horizontal', 'vertical'):
            raise ValueError('Undefined option for argument `layout`: {}. '
                             'Use either \'horizontal\' or \'vertical\'.'
                             .format(layout))
        width = '50%' if layout == 'horizontal' else '100%'
        height = '100%' if layout == 'horizontal' else '50%'
        self.m1 = Map(location=location, width=width, height=height,
                      left='0%', top='0%',
                      position='absolute', **kwargs)
        self.m2 = Map(location=location, width=width, height=height,
                      left='50%' if layout == 'horizontal' else '0%',
                      top='0%' if layout == 'horizontal' else '50%',
                      position='absolute', **kwargs)
        figure = Figure()
        figure.add_child(self.m1)
        figure.add_child(self.m2)
        # Important: add self to Figure last.
        figure.add_child(self)
        self.children_for_m2 = []
        self.children_for_m2_copied = []  # list with ids

    def _repr_html_(self, **kwargs):
        """Displays the HTML Map in a Jupyter notebook."""
        if self._parent is None:
            self.add_to(Figure())
            out = self._parent._repr_html_(**kwargs)
            self._parent = None
        else:
            out = self._parent._repr_html_(**kwargs)
        return out

    def add_child(self, child, name=None, index=None):
        """Add object `child` to the first map and store it for the second."""
        self.m1.add_child(child, name, index)
        if index is None:
            index = len(self.m2._children)
        self.children_for_m2.append((child, name, index))

    def render(self, **kwargs):
        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        figure.header.add_child(JavascriptLink('https://rawcdn.githack.com/jieter/Leaflet.Sync/master/L.Map.Sync.js'),  # noqa
                                name='Leaflet.Sync')

        super(DualMap, self).render(**kwargs)

        for child, name, index in self.children_for_m2:
            if child._id in self.children_for_m2_copied:
                # This map has been rendered before, child was copied already.
                continue
            child_copy = deep_copy(child)
            if isinstance(child_copy, LayerControl):
                child_copy.reset()
            self.m2.add_child(child_copy, name, index)
            # m2 has already been rendered, so render the child here:
            child_copy.render()
            self.children_for_m2_copied.append(child._id)

    def fit_bounds(self, *args, **kwargs):
        for m in (self.m1, self.m2):
            m.fit_bounds(*args, **kwargs)

    def keep_in_front(self, *args):
        for m in (self.m1, self.m2):
            m.keep_in_front(*args)