Пример #1
0
    def add_bubbles(self,
                    xycoords,
                    popups=None,
                    tooltips=None,
                    radius=1,
                    color='crimson',
                    fill_color='crimson',
                    fill=True,
                    **kwargs):

        if popups is None:
            popups = [None] * len(xycoords)

        if tooltips is None:
            tooltips = [None] * len(xycoords)

        if type(radius) == int:
            radius = [radius] * len(xycoords)

        if type(color) == str:
            color = [color] * len(xycoords)

        if type(fill_color) == str:
            fill_color = [fill_color] * len(xycoords)

        for i, gps in enumerate(xycoords):
            circle = Circle(location=gps,
                            popup=popups[i],
                            tooltip=tooltips[i],
                            radius=radius[i],
                            color=color[i],
                            fill=fill,
                            fill_color=fill_color[i],
                            **kwargs)
            circle.add_to(self.map)
Пример #2
0
def build_heat_map(data, sample):
    heat_map = Map(**MAP_DEFAULT_START_PARAMS)
    HeatMap(data[['lat', 'long']], radius=10).add_to(heat_map)
    if 'lat' in sample.columns:
        heat_map.add_child(
            Circle(*sample[['lat', 'long']].values, radius=1.1e5))
    return heat_map
Пример #3
0
def add_markers(wifi_connections, protections):
    for connection in wifi_connections:
        Circle(location=[connection.lat, connection.long],
               radius=20,
               color=colours[connection.protection],
               fill=True,
               fill_color=colours[connection.protection],
               weight=1).add_to(protections[connection.protection])
Пример #4
0
def get_beds_utilization_rate():
    df = get_df()
    _map = Map(location=[41.8781, -87.6298],
               tiles='cartodbpositron',
               zoom_start=10)
    for i in range(0, len(df)):
        Circle(location=[df.iloc[i]['Y'], df.iloc[i]['X']],
               radius=10000,
               fill=True,
               color=color(df.iloc[i]['BED_UTILIZATION'])).add_to(_map)
    _map.save('templates/bed_utilization_rate.html')
Пример #5
0
    def create_map(self):
        """
        Creates a map of earthquakes.

        """

        map1 = Map(tiles="Stamen Terrain")
        for i in self.locations:
            if self.place_damaged[i[0],
                                  i[1]] and self.place_damaged[i[0],
                                                               i[1]] > 0.5:

                if self.place_damaged[i[0], i[1]] > 5\
                        :
                    a = 'darkred'
                    to_write = 'The earthquake damage here is really high.'
                elif self.place_damaged[i[0], i[1]] > 3.5:
                    a = 'red'
                    to_write = 'Might cause some destructions.'
                elif self.place_damaged[i[0], i[1]] > 1.5:
                    a = 'orange'
                    to_write = "Some ground shaking but would't cause some big troubles"
                else:
                    a = 'yellow'
                    to_write = "Almost nothing changed, but probably make some inconvenience to people"
                if len(self.date) == 1:
                    sized = 4
                elif len(self.date) == 2:
                    sized = 50
                elif len(self.date) == 3:
                    sized = 1500
                map1.add_child(
                    Circle(location=[i[1], i[0]],
                           popup=to_write,
                           radius=10000 + sized * self.locations[i[0], i[1]],
                           color=a,
                           fill=True,
                           fill_color=a))
        map_name = "templates/Map_" + str(int(self.date[0]))

        if len(self.date) >= 2:
            map_name += '_' + str(int(self.date[1]))
        if len(self.date) == 3:
            map_name += "_" + str(int(self.date[2]))
        map_name += '.html'
        map1.save(map_name)
Пример #6
0
    def make_location_map(self):
        m = Map(location=self.updater.origin, zoom_start=10)
        Circle(location=self.updater.origin,
               fill_color='white',
               radius=self.updater.max_dist * 1609.34,
               weight=2,
               color="#000").add_to(m)
        CircleMarker(self.updater.origin,
                     popup="Origin",
                     radius=3,
                     fill=True,
                     color='red').add_to(m)

        for item in self.updater.in_range.values():
            if item.location.coords:
                CircleMarker(item.location.coords,
                             popup=item.location.name,
                             radius=3,
                             fill=True,
                             color='blue').add_to(m)
            else:
                print(f"{item.location.name} -- {item.location.address}")
        m.save("H-E-B map.html")
        webbrowser.open('H-E-B map.html')
Пример #7
0
def plot_point(folium_map: FoliumMap, coord: Tuple[float, float]):
    """Plot points at ``coord`` on ``folium_map``."""
    Circle(coord, 2).add_to(folium_map)
Пример #8
0
    for stop in ctrl_stops_cross.all_data:
        popup = Popup(f"{stop.primary} & {stop.secondary}<br>{stop.name_list_html}",
                      min_width=250, max_width=800)

        if stop.wheelchair_accessible:
            color = "green"
        else:
            color = "lightred"

        if use_marker:
            icon = Icon(color=color, icon_color="white", icon="bus", angle=0, prefix="fa")

            Marker(stop.coordinate, popup=popup, icon=icon).add_to(parent)
        else:
            Circle(stop.coordinate, 2, popup=popup, color=color).add_to(parent)


def plot_stops(folium_map: FoliumMap, clustered: bool = True):
    """
    Plot all the stops onto ``folium_map``.

    ``clustered`` determines if the stop will be clustered/expanded upon zoom.

    Could use customized color in the future for better rendering effect.
    """
    if clustered:
        parent = MarkerCluster().add_to(folium_map)
    else:
        parent = folium_map
Пример #9
0
    def Clicked_2(self):
        def percent(data, percent=None):
            index = []
            for i in percent:
                index.append(data.quantile(i))
            return index

        global df, df5, df6, gender_mean, female_mean, male_mean, user_subs, user_cust, user
        global ut_subs, ut_cust, ut_subs_fem, ut_subs_male, ut_cust_fem, ut_cust_male
        radioBtn = self.sender()
        if radioBtn.isChecked():
            if radioBtn.text() == 'Trip Duration':
                ##Average Trip Duration map
                maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                           zoom_start=10,
                           control_scale=True,
                           tiles="OpenStreetMap")
                try:
                    locations3a = df[[
                        'latitude_start', 'longitude_start', 'Trip Duration',
                        'Start Station', 'age'
                    ]].copy()
                    locations3 = locations3a.groupby('Start Station').mean()
                    locations3.dropna(subset=['Trip Duration'], inplace=True)
                    index = percent(locations3['Trip Duration'],
                                    percent=[0.01, 0.40, 0.75, 0.85, 0.98])
                    colormap = cm.LinearColormap(
                        colors=['blue', 'cyan', 'yellow', 'orange', 'red'],
                        vmin=locations3['Trip Duration'].quantile(0.01),
                        vmax=locations3['Trip Duration'].quantile(0.98),
                        caption='Average Trip Duration (m.)',
                        index=index)
                    locationlist3 = locations3.values.tolist()
                    group3 = FeatureGroup(name="Trip Duration")
                    for i in range(0, len(locationlist3)):
                        Circle(location=locationlist3[i][0:2],
                               radius=150,
                               fill=True,
                               color=colormap(locationlist3[i][2]),
                               popup=locations3[['Trip Duration', 'age'
                                                 ]].iloc[i]).add_to(group3)
                    group3.add_to(maps)
                    colormap.add_to(maps)
                except:
                    pass
                LayerControl().add_to(maps)
                data = io.BytesIO()
                maps.save(data, close_file=False)
                m = self.ui.webEngineView_3
                m.setHtml(data.getvalue().decode())
                m.resize(740, 520)
                maps.save("TripDuration.html")
                m.show()
                maps.save(data, close_file=True)

            # Gender map
            if radioBtn.text() == 'Gender Map':
                ##female percent
                maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                           zoom_start=10,
                           control_scale=True,
                           tiles="OpenStreetMap")
                try:
                    gm = gender_mean.dropna(subset=['count total'])
                    index = percent(gm['female percent'],
                                    percent=[0.01, 0.25, 0.60, 0.85, 0.99])
                    colormap = cm.LinearColormap(
                        colors=['blue', 'cyan', 'yellow', 'orange', 'red'],
                        vmin=gm['female percent'].quantile(0.01),
                        vmax=gm['female percent'].quantile(0.99),
                        caption='Female Percent',
                        index=index)
                    locationlist4 = gm[[
                        'latitude_start', 'longitude_start', 'female percent'
                    ]].values.tolist()
                    group4 = FeatureGroup(name="Female Percent")
                    pop = gm[[
                        'Trip Duration female', 'age female', 'count female',
                        'female percent'
                    ]]
                    for i in range(0, len(locationlist4)):
                        Circle(location=locationlist4[i][0:2],
                               radius=150,
                               fill=True,
                               color=colormap(locationlist4[i][2]),
                               popup=pop.iloc[i]).add_to(group4)

                    group4.add_to(maps)
                    colormap.add_to(maps)
                except:
                    pass
                LayerControl().add_to(maps)
                data = io.BytesIO()
                maps.save(data, close_file=False)
                m = self.ui.webEngineView_3
                m.setHtml(data.getvalue().decode())
                m.resize(740, 520)
                maps.save("FemalePercent.html")
                m.show()
                maps.save(data, close_file=True)

            ## age map
            if radioBtn.text() == 'Age Map':
                maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                           zoom_start=10,
                           control_scale=True,
                           tiles="OpenStreetMap")
                try:
                    age = df.groupby('Start Station').mean()
                    age.dropna(subset=['age'], inplace=True)
                    index = percent(age['age'],
                                    percent=[0.01, 0.25, 0.50, 0.75, 0.99])
                    colormap = cm.LinearColormap(
                        colors=['blue', 'cyan', 'yellow', 'orange', 'red'],
                        vmin=age['age'].quantile(0.01),
                        vmax=age['age'].quantile(0.99),
                        caption='Age Average',
                        index=index)
                    locationlist5 = age[[
                        'latitude_start', 'longitude_start', 'age'
                    ]].values.tolist()
                    group5 = FeatureGroup(name="Age Average")
                    pop = gender_mean[[
                        'age male', 'count male', 'age female', 'count female'
                    ]]
                    for i in range(0, len(locationlist5)):
                        Circle(location=locationlist5[i][0:2],
                               radius=150,
                               fill=True,
                               color=colormap(locationlist5[i][2]),
                               popup=pop.iloc[i]).add_to(group5)

                    group5.add_to(maps)
                    colormap.add_to(maps)
                except:
                    pass
                LayerControl().add_to(maps)
                data = io.BytesIO()
                maps.save(data, close_file=False)
                m = self.ui.webEngineView_3
                m.setHtml(data.getvalue().decode())
                m.resize(740, 520)
                maps.save("AgeAverage.html")
                m.show()
                maps.save(data, close_file=True)

            ## Trip Count
            if radioBtn.text() == 'Trip Count':
                maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                           zoom_start=10,
                           control_scale=True,
                           tiles="OpenStreetMap")

                count = df.groupby('Start Station').mean()
                count['count'] = df.groupby(
                    'Start Station')['Trip Duration'].count()
                count.dropna(subset=['count'], inplace=True)
                index = percent(count['count'],
                                percent=[0.05, 0.40, 0.75, 0.95])
                colormap = cm.LinearColormap(
                    colors=['blue', 'cyan', 'yellow', 'orange', 'red'],
                    vmin=count['count'].quantile(0.05),
                    vmax=count['count'].quantile(0.95),
                    caption='Trip Count Start Station',
                    index=index)
                locationlist6 = count[[
                    'latitude_start', 'longitude_start', 'count'
                ]].values.tolist()
                group6 = FeatureGroup(name="Trip Count")
                pop = count[['Trip Duration', 'count', 'age']]
                for i in range(0, len(locationlist6)):
                    Circle(location=locationlist6[i][0:2],
                           radius=150,
                           fill=True,
                           color=colormap(locationlist6[i][2]),
                           popup=pop.iloc[i]).add_to(group6)
                group6.add_to(maps)
                colormap.add_to(maps)
                LayerControl().add_to(maps)
                data = io.BytesIO()
                maps.save(data, close_file=False)
                m = self.ui.webEngineView_3
                m.setHtml(data.getvalue().decode())
                m.resize(740, 520)
                maps.save("TripCount.html")
                m.show()
                maps.save(data, close_file=True)

            ## User Type
            if radioBtn.text() == 'User Type':
                maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                           zoom_start=10,
                           control_scale=True,
                           tiles="OpenStreetMap")
                index = percent(user['subs percent'],
                                percent=[0.01, 0.10, 0.40, 0.70, 0.95])
                colormap = cm.LinearColormap(
                    colors=['blue', 'cyan', 'yellow', 'orange', 'red'],
                    vmin=user['subs percent'].quantile(0.01),
                    vmax=user['subs percent'].quantile(0.95),
                    caption='User Type: Subscriber (Percent)',
                    index=index)

                locationlist7 = user[[
                    'latitude_start', 'longitude_start', 'subs percent'
                ]].values.tolist()
                group7 = FeatureGroup(name="User Type")
                pop = user[['count subs', 'count cust', 'subs percent']]
                for i in range(0, len(locationlist7)):
                    Circle(location=locationlist7[i][0:2],
                           radius=150,
                           fill=True,
                           color=colormap(locationlist7[i][2]),
                           popup=pop.iloc[i]).add_to(group7)
                group7.add_to(maps)
                colormap.add_to(maps)
                LayerControl().add_to(maps)
                data = io.BytesIO()
                maps.save(data, close_file=False)
                m = self.ui.webEngineView_3
                m.setHtml(data.getvalue().decode())
                m.resize(740, 520)
                maps.save("UserType.html")
                m.show()
                maps.save(data, close_file=True)
Пример #10
0
from folium import plugins, Map, Circle, CircleMarker, PolyLine
from randomcoords import RandomCoords

center_point = [
    34.062400, -117.894900
]  # Defining the center of our map as well as our RandomCoords objects

# Making our first map, a 100km circle with 5000 points.
map1 = Map(location=center_point, zoom_start=12)

rc = RandomCoords(center=center_point, diameter=100, units='km')
for point in rc.generate_coords(num_coords=5000):
    CircleMarker(location=point, radius=2, color='blue').add_to(map1)

Circle(radius=50000, location=center_point, fill=False,
       color='red').add_to(map1)

map1.save(r'C:\Users\User\Desktop\big_map_km.html')

# Making our second map, a 10mi circle with 500 points.
map2 = Map(location=center_point, zoom_start=12)

rc2 = RandomCoords(center=center_point, diameter=10, units='mi')
for point in rc2.generate_coords(num_coords=500):
    CircleMarker(location=point, radius=2, color='blue').add_to(map2)

Circle(radius=8046, location=center_point, fill=False,
       color='red').add_to(map2)

map2.save(r'C:\Users\User\Desktop\smaller_map_mi.html')
                 tiles='cartodbpositron',
                 zoom_start=13)


def color_producer(val):
    if val <= 12:
        return 'forestgreen'
    else:
        return 'darkred'


### Bubble maps:Add a bubble map to the base map
for i in range(0, len(daytime_robberies)):
    Circle(location=[
        daytime_robberies.iloc[i]['Lat'], daytime_robberies.iloc[i]['Long']
    ],
           radius=20,
           color=color_producer(daytime_robberies.iloc[i]['HOUR'])).add_to(m_4)

### Heatmaps:Create a base map
m_5 = folium.Map(location=[42.32, -71.0589],
                 tiles='cartodbpositron',
                 zoom_start=12)

### Heatmaps:Add a heatmap to the base map
HeatMap(data=crimes[['Lat', 'Long']], radius=10).add_to(m_5)

### GeoDataFrame with geographical boundaries of Boston police districts
districts_full = gpd.read_file('./Data/Police_Districts.shp')
districts = districts_full[["DISTRICT", "geometry"]].set_index("DISTRICT")
Пример #12
0
def device_history_map(map_type='dynamic', dataframe=None, options=dict()):
    '''
    Creates a folium map with either location of devices or their "existence period"
    -------
    Parameters:
    map_type: String
        'dynamic'
        'dynamic' or 'static'. Whether is a dinamic map or not
    dataframe: Pandas Dataframe
        None
        Contains information about when the devices started posting data, ids, location.
        It follows the format of world_map in api device
    options: dict
        dict()

    Returns:
        Folium.Map object
    '''
    def coordinates(x):
        return [x['latitude'], x['longitude']]

    def color(x):
        iSCAPE_IDs = [19, 20, 21, 28]
        making_sense_IDs = [11, 14]
        SCK_21_IDs = [26]

        color = '#0019ff'

        try:
            if x['kit_id'] in iSCAPE_IDs: color = '#7dbd4c'
            elif x['kit_id'] in making_sense_IDs: color = '#f88027'
            elif x['kit_id'] in SCK_21_IDs: color = '#ffb500'
        except:
            print_exc()
            pass

        return color

    def validate(x):

        if x['last_reading_at'] is None: return False
        if x['added_at'] is None: return False
        if any(x['coordinates']) is None or any(
            [isnan(item) for item in x['coordinates']]):
            return False
        if map_type == 'dynamic':
            if x['date_list'] == []: return False

        return True

    def range_list(x):

        date_r = date_range(start=x['added_at'],
                            end=x['last_reading_at'],
                            normalize=True,
                            freq=options['period']).strftime('%Y-%m-%d')
        date_l = list()
        for item in date_r.values:
            date_l.append(str(item))

        return date_l

    dataframe['color'] = dataframe.apply(lambda x: color(x), axis=1)
    dataframe['coordinates'] = dataframe.apply(lambda x: coordinates(x),
                                               axis=1)

    options = dict_fmerge(config._map_def_opt, options)

    # Make map
    m = Map(
        location=options['location'],
        tiles=options['tiles'],
        zoom_start=options['zoom'],
    )

    if map_type == 'dynamic':
        dataframe['date_list'] = dataframe.apply(lambda x: range_list(x),
                                                 axis=1)
        dataframe['valid'] = dataframe.apply(lambda x: validate(x), axis=1)

        dataframe = dataframe[(dataframe['valid'] == True)]
        features = list()

        for sensor in dataframe.index:
            features.append({
                'type': 'Feature',
                'geometry': {
                    'type':
                    'LineString',
                    'coordinates':
                    [dataframe.loc[sensor, 'coordinates'][::-1]] *
                    len(dataframe.loc[sensor, 'date_list']),
                    'popup':
                    f'<a href="http://smartcitizen.me/kits/{sensor}">{sensor}</a>',
                },
                'properties': {
                    'times': dataframe.loc[sensor, 'date_list'],
                    'icon': options['icon'],
                    'iconstyle': {
                        'fillOpacity': options['fillOpacity'],
                        'fillColor': dataframe.loc[sensor, 'color'],
                        'stroke': options['stroke'],
                        'radius': options['radius']
                    },
                    'style': {
                        'weight': '0'
                    },
                    'id': 'man'
                }
            })

        TimestampedGeoJson(
            {
                'type': 'FeatureCollection',
                'features': features
            },
            period='P' + convert_rollup(options['period']),
            add_last_point=True,
            auto_play=False,
            loop=False,
            max_speed=options['max_speed'],
            loop_button=True,
            # date_options='YYYY/MM/DD',
            time_slider_drag_update=True,
            duration='P' + options['period']).add_to(m)

    elif map_type == 'static':

        dataframe['valid'] = dataframe.apply(lambda x: validate(x), axis=1)
        dataframe = dataframe[(dataframe['valid'] == True)]

        for sensor in dataframe.index:
            Circle(
                location=dataframe.loc[sensor, 'coordinates'],
                radius=options['radius'],
                color=dataframe.loc[sensor, 'color'],
                fill=True,
                fillOpacity=options['fillOpacity'],
                fillColor=dataframe.loc[sensor, 'color'],
                popup=
                f'<a href="http://smartcitizen.me/kits/{sensor}">{sensor}</a>'
            ).add_to(m)

    return m
Пример #13
0
def path_plot(self,
              channel=None,
              map_type='dynamic',
              devices='all',
              start_date=None,
              end_date=None,
              options=dict()):
    '''
    Creates a folium map showing a path
    Parameters
    -------
    channel: String
        None
        If None, shows path, otherwise, colored path with channel mapping
    map_type: String
        'dynamic'
        'dynamic' or 'static'. Whether is a dinamic map or not
    devices: list or 'all'
        List of devices to include, or 'all' from self.devices
    channel: String
        The channel to make the map from
    start_date, end_date: String
        Date convertible string
    options: dict()
        Possible keys are (default otherwise)
            location: list
                [41.400818, 2.1825157]
                Center map location
            tiles: (String)
                'Stamen Toner'
                Tiles for the folium.Map
            zoom: (float)
                2.5
                Zoom to start with in folium.Map
            period: 'String'
                '1W'
                Period for 'dynamic' map
            radius: float
                10
                Circle radius for icon
            fillOpacity: float
                1
                (<1) Fill opacity for the icon
            stroke: 'String'
                'false'
                'true' or 'false'. For icon's stroke
            icon: 'String'
                'circle'
                A valid folium.Map icon style
    Returns
    -------
        Folium.Map object
    '''

    # Set defaults
    options = dict_fmerge(config._map_def_opt, options)

    # Make features
    features = []
    if devices == 'all':
        mdev = self.devices
    else:
        mdev = list()
        for device in devices:
            if device in self.devices: mdev.append(device)
            else: std_out(f'Device {device} not found, ignoring', 'WARNING')

    if len(mdev) == 0:
        std_out('Requested devices not in test', 'ERROR')
        return None

    for device in mdev:
        chs = ['GPS_LAT', 'GPS_LONG']
        if channel is not None:
            if channel not in self.devices[str(device)].readings.columns:
                std_out(
                    f'Channel {channel} not in columns: {self.devices[str(device)].readings.columns}',
                    'ERROR')
                return None

            # Get bins
            minmax = False
            if not options['minmax']:
                if all([key not in channel for key in config._channel_bins]):
                    std_out(
                        f'Requested channel {channel} not in config mapped bins {config._channel_bins.keys()}.Using min/max mapping',
                        'WARNING')
                    minmax = True
            else:
                minmax = True

            if minmax:
                bins = linspace(
                    self.devices[str(device)].readings[channel].min(),
                    self.devices[str(device)].readings[channel].max(),
                    config._channel_bin_n)
            else:
                for bname in config._channel_bins.keys():
                    if bname in channel:
                        bins = config._channel_bins[bname]
                        break
            chs.append(channel)

        # Create copy
        dfc = self.devices[str(device)].readings[chs].copy()
        # Resample and cleanup
        # TODO THIS CAN INPUT SOME MADE UP READINGS
        dfc = clean(dfc.resample(options['period']).mean(), 'fill')

        # Make color column
        legend_labels = None
        if channel is not None:
            dfc['COLOR'] = cut(dfc[channel], bins, labels =\
                config._map_colors_palette)

            # Make legend labels
            legend_labels = {}
            for ibin in range(len(bins) - 1):
                legend_labels[f'{round(bins[ibin],2)} : {round(bins[ibin+1],2)}'] =\
                    config._map_colors_palette[ibin]
        else:
            dfc['COLOR'] = config._map_colors_palette[0]

        if start_date is not None:
            dfc = dfc[dfc.index > start_date]
        if end_date is not None:
            dfc = dfc[dfc.index < end_date]

        # Add point for each date
        for date in dfc.index:
            if date == dfc.index[-1]: break
            times = []

            color = str(dfc.loc[date, 'COLOR'])
            if color == 'nan' or isnan(dfc.loc[date, 'GPS_LONG'])\
            or isnan(dfc.loc[date, 'GPS_LAT']):
                std_out(f'Skipping point {date}', 'WARNING')
                continue

            geometry = {
                'type':
                'LineString',
                'coordinates':
                [[dfc.loc[date, 'GPS_LONG'], dfc.loc[date, 'GPS_LAT']],
                 [
                     dfc.loc[date + dfc.index.freq, 'GPS_LONG'],
                     dfc.loc[date + dfc.index.freq, 'GPS_LAT']
                 ]],
            }

            properties = {
                'icon':
                options['icon'],
                'iconstyle': {
                    'fillColor': color,
                    'fillOpacity': options['fillOpacity'],
                    'stroke': options['stroke'],
                    'radius': options['radius']
                },
                'device':
                device,
                'timestamp':
                date.strftime('%Y-%m-%dT%H:%M:%S'),
                "coordinates": [
                    dfc.loc[date + dfc.index.freq, 'GPS_LAT'],
                    dfc.loc[date + dfc.index.freq, 'GPS_LONG']
                ],
                'style': {
                    'color': color,
                    'stroke-width': options['stroke-width'],
                    'fillOpacity': options['fillOpacity']
                }
            }

            # Add reading to tooltip
            if channel is not None:
                properties['channel'] = channel
                properties['value'] = dfc.loc[date, channel]

            if map_type == 'dynamic':
                properties['times'] = [
                    date.strftime('%Y-%m-%dT%H:%M:%S'),
                    (date + dfc.index.freq).strftime('%Y-%m-%dT%H:%M:%S')
                ]

            features.append({
                'type': 'Feature',
                'geometry': geometry,
                'properties': properties
            })

    featurecol = {'type': 'FeatureCollection', 'features': features}

    # Make map
    if options['location'] == 'average':
        avg_long = dfc['GPS_LONG'].mean()
        avg_lat = dfc['GPS_LAT'].mean()
        loc = [avg_lat, avg_long]
    else:
        loc = options['location']

    m = Map(
        location=loc,
        tiles=options['tiles'],
        zoom_start=options['zoom'],
    )

    if map_type == 'static':
        # TODO WORKAROUND UNTIL GEOJSON ACCEPTS MARKERS
        if options['markers']:
            for feature in features:
                Circle(location=[
                    feature['geometry']['coordinates'][0][1],
                    feature['geometry']['coordinates'][0][0]
                ],
                       fill='true',
                       radius=feature['properties']['iconstyle']['radius'],
                       color=feature['properties']['iconstyle']['fillColor'],
                       fill_opacity=feature['properties']['iconstyle']
                       ['fillOpacity']).add_to(m)

        if channel is not None:
            fields = ["device", "channel", "timestamp", "coordinates", "value"]
            aliases = [
                "Device:", "Sensor:", "Timestamp:", "Coordinates:", "Reading:"
            ]
        else:
            fields = ["device", "timestamp", "coordinates"]
            aliases = ["Device:", "Timestamp:", "Coordinates:"]

        popup = GeoJsonPopup(
            fields=fields,
            aliases=aliases,
            localize=True,
            labels=True,
            max_width=800,
        )

        tooltip = GeoJsonTooltip(
            fields=fields,
            aliases=aliases,
            localize=True,
            sticky=True,
            labels=True,
            style="""
                background-color: #F0EFEF;
                border: 1px solid gray;
                border-radius: 1px;
                box-shadow: 2px;
            """,
            max_width=800,
        )

        GeoJson(
            featurecol,
            tooltip=tooltip,
            popup=popup,
            style_function=lambda x: {
                'color': x['properties']['style']['color'],
                'weight': x['properties']['style']['stroke-width'],
                'fillOpacity': x['properties']['style']['fillOpacity']
            },
        ).add_to(m)

    elif map_type == 'dynamic':
        TimestampedGeoJson(featurecol,
                           period='PT' + convert_rollup(options['period']),
                           add_last_point=True,
                           auto_play=False,
                           loop=False,
                           max_speed=options['max_speed'],
                           loop_button=True,
                           time_slider_drag_update=True).add_to(m)

    else:
        std_out(f'Not supported map type {map_type}', 'ERROR')
        return None

    if options['minimap']:
        minimap = MiniMap(toggle_display=True, tile_layer=options['tiles'])
        minimap.add_to(m)

    if options['legend'] and not legend_labels is None:

        templateLoader = FileSystemLoader(searchpath=join(dirname(__file__),\
            'templates'))
        templateEnv = Environment(loader=templateLoader)
        template = templateEnv.get_template("map_legend.html")

        filled_map_legend = template.render(legend_labels=legend_labels)

        map_legend_html = '{% macro html(this, kwargs) %}'+\
            filled_map_legend+\
            '{% endmacro %}'

        legend = element.MacroElement()
        legend._template = element.Template(map_legend_html)

        m.get_root().add_child(legend)

    return m
Пример #14
0
                    color='red').add_to(m_2)


# Adding a map to visualize earthquake depth
def color_producer(val):
    if val <= 20:
        return 'darkred'
    else:
        return 'forestgreen'


# Adding a bubble map to the base map
for i in range(0, len(earthquakes)):
    Circle(location=[
        earthquakes.iloc[i]['Latitude'], earthquakes.iloc[i]['Longitude']
    ],
           radius=20,
           color=color_producer(earthquakes.iloc[i]['Depth'])).add_to(m_2)

# View the map
embed_map(m_2, 'q_2.html')

# GeoDataFrame with prefecture boundaries
prefectures = gpd.read_file(
    "../input/geospatial-learn-course-data/japan-prefecture-boundaries/japan-prefecture-boundaries/japan-prefecture-boundaries.shp"
)
prefectures.set_index('prefecture', inplace=True)
prefectures.head(10)

# DataFrame containing population of each prefecture
population = pd.read_csv(
Пример #15
0
    def get_prediction(self):
        """
        Logical assumption about nearest earthquakes based on last month - 2 month information.
        """

        now = datetime.datetime.now()
        now = list(map(int, str(now.date()).split('-')))
        now.reverse()
        days = 0

        if now[-2] in [2, 4, 6, 8, 9, 11]:
            for day in range(now[-3], 31):
                days += 1
                self.get_earthquakes_for_text(
                    [day, int(now[-2]) - 1,
                     int(now[-1])])
        elif now[-2] == 3:
            for day in range(now[-3], 28):
                days += 1
                self.get_earthquakes_for_text(
                    [day, int(now[-2]) - 1,
                     int(now[-1])])
        elif now[-2] == 1:
            for day in range(now[-3], 31):
                days += 1
                self.get_earthquakes_for_text([day, 12, int(now[-1]) - 1])
        else:
            for day in range(now[-3], 30):
                days += 1
                self.get_earthquakes_for_text(
                    [day, int(now[-2]) - 1,
                     int(now[-1])])
        for day in range(1, int(now[-3])):
            days += 1
            self.get_earthquakes_for_text([day, int(now[-2]), int(now[-1])])
        map1 = Map()

        for place in self.places:
            if place in self.place_damaged:
                if self.place_damaged[place] - self.place_min_damage[place\
                        ] > self.place_max_damage[place] - self.place_damaged[place]:
                    self.place_damaged[place] = (
                        self.place_damaged[place] +
                        self.place_min_damage[place]) / 2
                elif place in self.place_damaged:
                    self.place_damaged[place] = (
                        self.place_damaged[place] +
                        self.place_min_damage[place]) / 2
                self.chance[place] = len(self.places[place]) / days
                if self.chance[place] > 0.1:
                    if self.place_damaged[place] > 0.5:
                        if self.chance[place] * 100 > 100:
                            self.chance[place] = 0.99
                        to_write = """"With chance {}% there would be earthquake in {} with probable power cl\
ose to {}""".format(
                            str(self.chance[place] * 100)[0:5], place,
                            str(self.place_damaged[place])[0:5])
                        if self.chance[place] > 0.8:
                            chances = 'darkred'
                        elif self.chance[place] > 0.6:
                            chances = 'red'
                        elif self.chance[place] > 0.4:
                            chances = 'orange'
                        else:
                            chances = 'yellow'
                        a = self.places[place][0].coordinates
                        map1.add_child(
                            Circle(location=[a[1], a[0]],
                                   popup=to_write,
                                   radius=10000,
                                   color=chances,
                                   fill=True,
                                   fill_color=chances))
        map1.save('templates/Map_prediction.html')
Пример #16
0
import folium
import pandas as pd
from folium import Circle

hospitals = pd.read_csv("hos.csv")
bubble_map = folium.Map(location=[13.0700, 80.2492],
                        tiles='cartodbpositron',
                        zoom_start=11)


def color_producer(val):
    if val <= 500:
        return "forestgreen"
    else:
        return "darkred"


for i in range(0, len(hospitals)):
    Circle(location=[
        hospitals.iloc[i]['latitude'], hospitals.iloc[i]['longitude']
    ],
           radius=100,
           color=color_producer(
               hospitals.iloc[i]["capacity"])).add_to(bubble_map)

# Display the map
bubble_map.save("kk.html")
Пример #17
0
     location = [row['Latitude'], row['Longitude']]
     popup = '<div style="width:300">' + '<STRONG>' + '<h3>' + str(
         row['Province/State']
     ) + '</h3>' + '<br>' + '<p>' + 'Confirmed-' + str(
         row['Confirmed']) + '<br>' + 'Deaths-' + str(
             row['Deaths']) + '<br>' + 'Recovered-' + str(
                 row['Recovered']) + '</p>' + '</STRONG>' + '</div>'
     mc.add_child(
         Marker(location=location,
                popup=popup,
                icon=folium.Icon(color='red', icon='info-sign')))
     radius = 15000 + int(row['Confirmed']) * 20
     mc1.add_child(
         Circle(location=location,
                popup=popup,
                radius=radius,
                fill_colour='#FF0000',
                color="red",
                fill=True))
 else:
     location = [row['Latitude'], row['Longitude']]
     popup = '<div style="width:300">' + '<STRONG>' + '<h3>' + row[
         'Country/Region'] + '</h3>' + '<br>' + '<p>' + 'Confirmed-' + str(
             row['Confirmed']) + '<br>' + 'Deaths-' + str(
                 row['Deaths']) + '<br>' + 'Recovered-' + str(
                     row['Recovered']) + '</p>' + '</STRONG>' + '</div>'
     mc.add_child(
         Marker(location=location,
                popup=popup,
                icon=folium.Icon(color='red', icon='info-sign')))
     radius = 15000 + int(row['Confirmed']) * 20
     mc1.add_child(