Example #1
0
 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
Example #2
0
    def _generateMarkers(self):
        popupTemplate = """
        <head>
        <style>
        table {
            border: 1px solid black;
            border-radius: 25px;
        }
        </style>
        </head>
        <body>
        <table style="width:100%">
              <tr>
                <th>Key</th>
                <th>Value</th>
              </tr>
              ROWS
            </table>

        </body>
        """
        # tableTemplate = """<table style="width:100%"><tr><th>key</th><th>value</th></tr>ROWS</table>"""
        rowTemplate = """<tr><td>KEY</td><td>VALUE</td></tr>"""
        markers = []
        for _, row in self.df.iterrows():
            if isinstance(row[self.lon], numbers.Number) and isinstance(
                    row[self.lat], numbers.Number):
                markerTemp = ipyleaflet.Marker(
                    location=[row[self.lat], row[self.lon]], draggable=False)
                # popup information
                message = HTML()
                rowList = []
                for x, y in row.iteritems():
                    if x in self.properties:
                        str_x = re.escape(str(x))
                        str_y = re.escape(str(y))
                        rowTemp = re.sub('VALUE', str_y,
                                         re.sub('KEY', str_x, rowTemplate))
                        rowTemp = re.sub(r'\\(.)', r'\1', rowTemp)
                        rowList.append(rowTemp)
                message.value = re.sub(
                    r'\\(.)', r'\1',
                    re.sub('ROWS', ''.join(rowList), popupTemplate))
                message.placeholder = ''
                message.description = ''
                markerTemp.popup = message
                # style of marker
                markerTemp.layout = {'padding': '1px'}
                markers.append(markerTemp)
        return markers
Example #3
0
    def show_m():

        multipoly = []
        multycent = []
        geom = spatial_utils.transform_geometry(info_data)
        poly = geom['geom'][0]['coordinates'][0]
        #     poly = spatial_utils.swap_xy(geom['coordinates'][0])[0]
        multipoly.append(poly)
        centroid = spatial_utils.centroid(poly)
        multycent.append(centroid)

        centroid = spatial_utils.centroid(multycent)
        m = Map(center=centroid,
                zoom=16,
                basemap=basemaps.OpenStreetMap.Mapnik)

        polygon = Polygon(locations=multipoly,
                          name='Parcel polygon',
                          color="yellow",
                          fill_color=None)

        m.add_layer(polygon)
        basemap2 = basemap_to_tiles(basemaps.Esri.WorldImagery)

        poly_text = HTML()
        poly_text.value = f"""Parcel ID: {pid}<br>
                                    Crop name: {crop_name}<br>
                                    Area: {area:.2f} sqm<br>
                                    Coordinates: {centroid}
                                    """
        poly_text.placeholder = "HTML"
        poly_text.description = ""

        # Popup with a given location on the map:
        poly_popup = Popup(child=poly_text,
                           close_button=False,
                           auto_close=False,
                           close_on_escape_key=False)
        m.add_layer(poly_popup)

        polygon.popup = poly_popup  # Popup associated to a layer

        # Layers control
        show_poly = Checkbox(value=True,
                             description='Polygon',
                             indent=False,
                             layout=Layout(width='140px'))
        show_sat = Checkbox(value=False,
                            description='High res basemap',
                            indent=False,
                            layout=Layout(width='140px'))

        def polygon_changed(b):
            try:
                if show_poly.value is True:
                    m.add_layer(polygon)
                else:
                    m.remove_layer(polygon)
            except Exception:
                pass

        show_poly.observe(polygon_changed)

        def show_sat_changed(b):
            try:
                if show_sat.value is True:
                    m.add_layer(basemap2)
                else:
                    m.remove_layer(basemap2)
            except Exception:
                pass

        show_sat.observe(show_sat_changed)

        try:
            df = raster_utils.create_df(ci_path, pid, ci_band.value)

            geotiff = normpath(
                join(ci_path, f"{df['imgs'][0]}.{ci_band.value[0]}.tif"))
            bounds = raster_utils.bounds(geotiff)

            images = {}
            for i, row in df.iterrows():
                str_date = str(row['date'].date()).replace('-', '')
                img_tc = normpath(
                    join(ci_path,
                         f"{('').join(ci_band.value)}_{str_date}.png"))

                # Create false color image if it does not exist
                # Merge bands (images path, export image path, bands list)
                if not isfile(img_tc):
                    imgs_path = normpath(join(ci_path, row['imgs']))
                    raster_utils.merge_bands(imgs_path, img_tc, ci_band.value)

                if bool(config.get_value(['set', 'jupyterlab'])) is True:
                    jlab_path = os.getcwd().replace(os.path.expanduser("~"),
                                                    '')
                    image_path = normpath(join(f'files{jlab_path}', img_tc))
                else:
                    image_path = img_tc

                # print('image_path: ', image_path)
                images[i] = ImageOverlay(url=image_path,
                                         name=str_date,
                                         bounds=(bounds))

            # Time slider
            slider = IntSlider(value=1,
                               min=1,
                               max=len(images),
                               step=1,
                               description=str(df['date'][0].date()),
                               continuous_update=False,
                               orientation='horizontal',
                               readout=True,
                               readout_format='d')
            show_chip = Checkbox(value=True,
                                 description='Chip image',
                                 indent=False,
                                 layout=Layout(width='140px'))

            def on_ci_band_change(change):
                pass

            ci_band.observe(on_ci_band_change, 'value')

            def show_chip_changed(b):
                try:
                    if show_chip.value is True:
                        m.add_layer(images[slider.value - 1])
                    else:
                        m.remove_layer(images[slider.value - 1])
                except Exception:
                    pass

            show_chip.observe(show_chip_changed)

            # Slider control
            play = Play(
                value=1,
                min=1,
                max=len(images),
                step=1,
                interval=1000,
                description="Press play",
            )

            def slider_changed(b):
                if show_chip.value is True:
                    try:
                        m.substitute_layer(images[b['old'] - 1],
                                           images[b['new'] - 1])
                    except Exception:
                        pass
                    slider.description = str(df['date'][slider.value -
                                                        1].date())

            slider.observe(slider_changed)
            jslink((play, 'value'), (slider, 'value'))
            time_box = HBox([slider, play])
            time_control = WidgetControl(widget=time_box,
                                         position='bottomleft')
            m.add_control(time_control)
            m.add_layer(images[0])

            map_options = VBox([show_poly, show_chip, show_sat])
        except Exception as err:
            map_options = VBox([show_poly, show_sat])
            print(err)

        layers_control = WidgetControl(widget=map_options,
                                       position='topright',
                                       max_width=150)
        m.add_control(layers_control)
        return m
Example #4
0
 def f(location):
     message = HTML()
     message.description = "Station ID"
     message.value = str(self.marker_info[location])
     message.placeholder = ""
     return message
Example #5
0
def visualize():
    center = location_latlongs[1]

    m = Map(center=center, zoom=8)
    icon1 = Icon(
        icon_url='https://img.icons8.com/ultraviolet/40/000000/map-pin.png',
        icon_size=[40, 40],
        icon_anchor=[20, 40])
    icon2 = Icon(
        icon_url='https://img.icons8.com/officel/40/000000/map-pin.png',
        icon_size=[40, 40],
        icon_anchor=[20, 40])
    icon3 = Icon(
        icon_url=
        'http://icons.iconarchive.com/icons/custom-icon-design/flatastic-6/256/Circle-icon.png',
        icon_size=[10, 10],
        icon_anchor=[5, 5],
        shadow_size=[5, 5])

    line = Polyline(locations=[[
        path_latlongs,
    ]],
                    color="#669df6",
                    fill=False,
                    weight=2,
                    stroke=True)

    m.add_layer(line)

    style = {'text-align': 'left', 'description_width': '150px'}
    i = 0
    while i < len(location_latlongs):
        if i == 0:
            message = HTML()
            message.placeholder = "Source"
            message.description = "Source" + "<br>Node ID: " + location_latlongs[
                i][2] + "<br>Lat:   " + str(
                    location_latlongs[i][1]) + "<br>Long:  " + str(
                        location_latlongs[i][0])
            message.style = style
            marker = Marker(location=location_latlongs[i],
                            draggable=False,
                            title="Source",
                            icon=icon1,
                            rise_on_hover=True,
                            z_index_offset=100)
            m.add_layer(marker)
            marker.popup = message

        elif (len(location_latlongs) - i) == 1:
            message = HTML()
            message.placeholder = "Destination"
            message.description = "Destination" + "<br>Node ID: " + location_latlongs[
                i][2] + "<br>Lat:   " + str(
                    location_latlongs[i][1]) + "<br>Long:  " + str(
                        location_latlongs[i][0])
            message.style = style
            marker = Marker(location=location_latlongs[i],
                            draggable=False,
                            title="Destination",
                            icon=icon2,
                            rise_on_hover=True)
            m.add_layer(marker)
            marker.popup = message

        else:
            message = HTML()
            message.placeholder = "Waypoint"
            message.description = "Waypoint: " + str(
                i) + "" + "<br>Node ID: " + location_latlongs[i][
                    2] + "<br>Lat:   " + str(
                        location_latlongs[i][1]) + "<br>Long:  " + str(
                            location_latlongs[i][0])
            message.style = style
            marker = Marker(location=location_latlongs[i],
                            draggable=False,
                            icon=icon3,
                            title="Waypoint",
                            rise_on_hover=True)
            m.add_layer(marker)
            marker.popup = message
        i += 1

    return (m)