Exemplo n.º 1
0
def show_map():
    latitude = 48.445
    longitude = 21.687

    np.random.seed(3141592)
    initial_data = (
        np.random.normal(size=(300, 2)) * np.array([[0.003, 0.003]]) +
        np.array([[latitude, longitude]]))

    move_data = np.random.normal(size=(300, 2)) * 0.00001

    data = [(initial_data + move_data * i).tolist() for i in range(100)]

    weight = 1  # default value
    for time_entry in data:
        for row in time_entry:
            row.append(weight)

    mapa = folium.Map([48.726, 21.249], tiles='OpenStreetMap', zoom_start=14)
    hm = HeatMapWithTime(data, auto_play=True, max_opacity=0.8, radius=5)
    hm.add_to(mapa)

    ref = db.reference('vines')
    result = ref.get()
    for res in result:
        folium.Marker(location=[
            float(result[res]['latitude']),
            float(result[res]['longitude'])
        ],
                      popup=result[res]['class'],
                      icon=folium.Icon(color='green')).add_to(mapa)

    mapa.save('mapa.html')
    return send_file('mapa.html')
Exemplo n.º 2
0
    def get_heatmapWithTime(self):

        data = self.og_data
        data['hour']=data['datetime'].apply(lambda x: x.hour)
        locations = {
        "Torino": [45.0781, 7.6761],
        "Amsterdam": [52.3676, 4.9041],
        "Austin": [30.2672, -97.7431],
        "Berlin": [52.5200, 13.4050],
        "Calgary": [51.0447, -114.0719],
        "Columbus": [39.9612, -82.9988],
        "Denver": [39.7392, -104.9903],
        "Firenze": [43.7696, 11.2558],
        "Frankfurt": [50.1109, 8.6821],
        "Hamburg": [53.5511, 9.9937]
        }

        _map = folium.Map(location=locations[self.parametro],
                        tiles='Stamen Toner', 
                        zoom_start = 12) 
    
        heat_df = data[['hour','lat','lng']]
        heat_df = heat_df.dropna(axis=0, subset=['hour','lat','lng'])

        lat_long_list = []
        for i in range(0,24):
            temp=[]
            for index, instance in heat_df[heat_df['hour'] == i].iterrows():
                temp.append([instance['lat'],instance['lng']])
            lat_long_list.append(temp)


        HeatMapWithTime(lat_long_list,radius=7,auto_play=True, position='bottomright').add_to(_map)

        return _map
Exemplo n.º 3
0
def heapMapTime():
    #Create the map
    start_coords = (-34.60, -58.42)
    folium_map = folium.Map(location=start_coords, zoom_start=13)

    # Seleccionamos solo las columnas de coordenadas validas para la fecha seleccionada
    df = initDataFrame()
    # Seleccionamos solo las columnas de coordenadas validas para la fecha seleccionada
    df = df[(df['latitud'] != 0) & (df['longitud'] != 0) & (df['anho'] == 2018)
            & (df['mes'] <= 3) & (df['solo_hora'] != 99)]

    #Creamos la lista de 24 horas
    df_hour_list = []
    for hour in df.solo_hora.sort_values().unique():
        df_hour_list.append(df.loc[df.solo_hora == hour,
                                   ['latitud', 'longitud', 'count']].groupby([
                                       'latitud', 'longitud'
                                   ]).sum().reset_index().values.tolist())

    #Creamos y agregamos el heatmap por horas
    HeatMapWithTime(df_hour_list,
                    radius=9,
                    gradient={
                        0.2: 'blue',
                        0.4: 'lime',
                        0.6: 'orange',
                        1: 'red'
                    },
                    min_opacity=0.1,
                    max_opacity=0.8,
                    use_local_extrema=True).add_to(folium_map)

    #Save in html
    folium_map.save('static/mapWithTime.html')
    return render_template('mapa2.html', current_time=int(time.time()))
Exemplo n.º 4
0
def heatmap_with_time(df: pd.DataFrame,
                      geo_wkt_col: str,
                      time_col: str,
                      agg_unit: str = MINUTE_AGG) -> HeatMapWithTime:
    """
    A visualization utility function for visualizing a timed-geographic layer with a folium's HeatMapWithTime.
    The function aggregates the times correctly and inserts the parameters correctly into the object.
    Args:
        df: The dataframe we want to visualize
        geo_wkt_col: The geographic column's name, holding wkt objects
        time_col: The time column's name
        agg_unit: The time unit for the aggregation

    Returns:
        A HeatMapWithTime object to use with a folium map
    """
    df = df[[geo_wkt_col, time_col]].copy()
    df[VIS_GEO_SHP] = df[geo_wkt_col].apply(lambda x: loads(x))
    df = _aggregate_datetime(df, time_col, VIS_AGG_TIME, agg_unit)

    time_groupby_dict = df.groupby(VIS_AGG_TIME).groups
    time_index = sorted(list(time_groupby_dict.keys()))
    data = []
    for t in time_index:
        data.append(
            list(
                map(lambda shp: [shp.centroid.y, shp.centroid.x],
                    df.iloc[time_groupby_dict[t]][VIS_AGG_TIME])))
    time_index_str = [dt.strftime('%Y-%m-%d  %H:%M') for dt in time_index]

    return HeatMapWithTime(data,
                           index=time_index_str,
                           auto_play=True,
                           max_opacity=0.5)
Exemplo n.º 5
0
def main():
    # Create Heatmap
    curr_dir = os.getcwd()
    confirmed_path = curr_dir + '/data/time_series_covid_19_confirmed.csv'
    death_path = curr_dir + '/data/time_series_covid_19_deaths.csv'
    recovered_path = curr_dir + '/data/time_series_covid_19_recovered.csv'

    map = Map(confirmed_path, death_path, recovered_path)
    days = map.parse_data_by_day()

    HeatMapWithTime(days,
                    radius=10,
                    gradient={
                        0.1: '#99FFFF',
                        0.2: '#66FF66',
                        0.4: '#FFFF66',
                        0.6: '#FF9933',
                        0.8: '#FF0000',
                        1.0: '#990000'
                    },
                    min_opacity=0.5,
                    max_opacity=1,
                    use_local_extrema=True,
                    min_speed=5,
                    auto_play=True).add_to(map.map)

    map.save_map()

    # Host html on localhost
    run_server()
Exemplo n.º 6
0
def folium_moving():
    df = df_ny_box()
    timezone_name = 'America/New_York'
    time_column = "pickup_datetime"
    df.index = pd.to_datetime(df[time_column])
    df.index = df.index.tz_convert(timezone_name)
    df["dow"] = df.index.weekday
    df["hour"] = df.index.hour
    df["month"] = df.index.month
    df["year"] = df.index.year
    df.reset_index(drop=True)
    gradient = {0.2: 'blue', 0.4: 'lime', 0.6: 'orange', 1: 'red'}

    heatmap_data_by_hour = []
    __df__ = df.copy()
    for hour in df.hour.sort_values().unique():
        _df = __df__[__df__.hour == hour][[
            'pickup_latitude', 'pickup_longitude', 'passenger_count'
        ]].groupby(['pickup_latitude',
                    'pickup_longitude']).sum().reset_index().values.tolist()
        heatmap_data_by_hour.append(_df)

    center_location = [40.758896, -73.985130]
    m2 = folium.Map(location=center_location,
                    control_scale=True,
                    zoom_start=11)
    HeatMapWithTime(heatmap_data_by_hour,
                    radius=5,
                    gradient=gradient,
                    min_opacity=0.5,
                    max_opacity=0.8,
                    use_local_extrema=False).add_to(m2)
    return m2
Exemplo n.º 7
0
def gen_heat_map(df_strava_travs_sliced):
    #First handle empty sliced df case. Create a generic zoomed out map with additional features
    if len(df_strava_travs_sliced) == 0:
        m = folium.Map(location=[36, -108], zoom_start=4, control_scale=True)
        folium.TileLayer('stamenterrain').add_to(m)
        m.save('map.html'
               )  #Save map without routes or markers and create dash layout
        return html.Iframe(id='mainview',
                           srcDoc=open('map.html', 'r').read(),
                           width='100%',
                           height='100%')
    #Slice not empty:
    #Create map based on staring location of last run
    init_coord = df_strava_travs_sliced.iloc[-1]['start_latlng']
    init_coord = ast.literal_eval(init_coord)
    m = folium.Map(location=init_coord, zoom_start=12, control_scale=True)
    folium.TileLayer('stamenterrain').add_to(m)
    #Initilaize arrays to store heatmap parameters
    heat_coords = []
    heat_date_ind = []
    for i in df_strava_travs_sliced.index:
        route_coord = polyline.decode(
            df_strava_travs_sliced.loc[i]['map.summary_polyline'])
        route_coord = [[i[0], i[1]] for i in route_coord]
        #Estimate number of splits
        cnt_splits = max(
            round(m_to_mi(df_strava_travs_sliced.loc[i]['distance'])), 1)
        coords_in_split = len(
            route_coord
        ) // cnt_splits  #Count number of coorindates to include in split
        route_coord = [
            route_coord[x:x + coords_in_split]
            for x in range(0, len(route_coord), coords_in_split)
        ]
        heat_coords.extend(route_coord)  #Add coordinates into list
        heat_date_ind.extend(
            [s_to_easyDate(df_strava_travs_sliced.loc[i]['event_date'][0:10])
             ] * len(route_coord))  #Get date as heatmap time index
    heat_coords_flat = [item for sublist in heat_coords for item in sublist]
    #Construct HeatMap
    HeatMap(heat_coords_flat, radius=6).add_to(m)
    #Construct HeatMap with time
    HeatMapWithTime(heat_coords,
                    heat_date_ind,
                    radius=12,
                    min_opacity=2,
                    max_opacity=4,
                    min_speed=5,
                    max_speed=12,
                    speed_step=1).add_to(m)
    #Save the map and create the mainview
    m.save('map.html')
    return html.Iframe(id='mainview',
                       srcDoc=open('map.html', 'r').read(),
                       width='100%',
                       height='100%')
Exemplo n.º 8
0
def generate_hotmap(data, name):
    '''
    Generate dynamic hotmap with input data and save as a html file.
    :param data: a 3-d list of [[[latitude, longitude, average_speed]]] for each hour for each location
    :param name: a str
    :return: no return
    '''
    map_osm = folium.Map(location=[31.2234, 121.4814], zoom_start=10)
    HeatMapWithTime(data, radius=10).add_to(map_osm)
    map_osm.save(name)
Exemplo n.º 9
0
def heatmap(gdf,
            geometry_column='geometry',
            with_time=False,
            time_column='Year',
            name=None,
            show=False,
            basemap=None,
            **kwargs):
    """
    Create a heatmap or a heatmap with time from a geodataframe of points.

    :param gdf: Geodataframe with points as the geometry type.
    :param geometry_column: The geometry column of the gdf. Defaults to 'geometry'
    :param start_color: The start color, defaults to 'white'
    :param end_color: The end color, defaults to the MI blue
    :param with_time: If true, plot a heat map with time, not just a heat map.
    :param time_column: The column used to specify the years of the data, defaults to 'Year'
    :param str name: Defaults to None. If not None, will generate a FeatureGroup with this name and return that instead of
        the GeoJson object.
    :param bool show: Defaults to False. The show parameter for the FeatureGroup that the GeoJson will be added to.
    :param folium.Map basemap: Defaults to None. If not none, will add the GeoJson or FeatureGroup to the supplied basemap.
    :param **kwargs: kwargs to be passed onto the 'heatmap' or 'heatmapwithtime' folium constructors.
    :return: HeatMap object or FeatureGroup
    """

    if with_time:
        all_points = []
        time_periods = sorted(gdf[time_column].unique().tolist())
        for time_period in time_periods:
            points = gdf.loc[gdf[time_column] == time_period, geometry_column]
            points = [
                utilities.simple.retrieve_coords(point) for point in points
            ]
            all_points.append(points)
        result = HeatMapWithTime(all_points, index=time_periods, **kwargs)

    else:
        points = [
            utilities.simple.retrieve_coords(point)
            for point in gdf[geometry_column]
        ]
        result = HeatMap(points, **kwargs)

    if name is not None:
        feature_group = folium.FeatureGroup(name, show=show)
        result.add_to(feature_group)
        if basemap is not None:
            feature_group.add_to(basemap)
        return feature_group
    else:
        if basemap is not None:
            result.add_to(basemap)
        return result
Exemplo n.º 10
0
def generate_map(server=False):
    tmp = path + "/corona.html"

    df = pd.read_csv(path + '/gps_dated/gps_dated.csv')
    df = df.loc[df.index.repeat(df.total)]

    dates = df.date.unique()
    heat = []

    for i in dates:
        tmp_df = df.loc[df['date'] == i]
        tmp_heat = [[row["lat"], row["lon"]] for idx, row in tmp_df.iterrows()]
        heat.append(tmp_heat)

    folium_map = folium.Map(location=[df.lat.mean(),
                                      df.lon.mean()],
                            zoom_start=4.4,
                            attr="CoViD19 no Brasil Agora")

    folium_map.add_child(
        HeatMapWithTime(heat,
                        index=list(dates),
                        auto_play=True,
                        name='Coronavirus'))

    for i in dates:
        tmp_df = df.loc[df['date'] == i]
        mk = MarkerCluster(name='Cluster ' + i, show=False)
        for lat, lon in zip(tmp_df.lat, tmp_df.lon):
            folium.CircleMarker(
                location=[lat, lon],
                radius=(10) / 2,
                fill_opacity=0.9,
                fill_color='#3186cc',
            ).add_to(mk)
        folium_map.add_child(mk)
    folium_map.add_child(folium.LayerControl())

    f.write("Saving html...\n")
    try:
        folium_map.save(tmp)
        f.write("Saved!\n")
    except:
        f.write("Error in saving process!!!\n")

    if (server):
        with open(tmp) as fi:
            folium_map_html = fi.read()
        run_html_server(folium_map_html)
Exemplo n.º 11
0
def plotHeatMap(values, date_range):
    base_map = folium.Map(location=[-31.420082, -64.188774])
    HeatMapWithTime(values,
                    index=date_range,
                    radius=25,
                    gradient={
                        0.0: 'blue',
                        0.2: 'lime',
                        0.4: 'orange',
                        1: 'red'
                    },
                    auto_play=True,
                    max_opacity=1).add_to(base_map)
    filename = tempfile.NamedTemporaryFile(prefix='heatmap_').name + '.html'
    base_map.save(filename)
    webbrowser.open(filename)
Exemplo n.º 12
0
    def generate_heat_map_with_time(
        self,
        style: int = 6,
        zoom_start: int = 12,
        time_var: str = "hours",
        time_max_val: int = 24,
    ):
        """
        Generates a interactive HeatMap which enables a geographic visualization by time.

        :param style: indicates which style of the map to be used
        :type style: int
        :param zoom_start: set the initial zoom of the map
        :type zoom_start: int
        :param time_var: the label of the time column by which the data is analyzed by
        :type time_var: str
        :param time_max_val: the maximal time value to be shown
        :type time_max_val: int
        :return:
        """
        junk_coord = (
            -360
        )  # Junk values are inserted here such that the time variable matches the time filter
        self._generate_base_map(style, zoom_start)
        df_tmp = self.data[[self.lat, self.lon, time_var]]
        time_list = [[[
            junk_coord, junk_coord
        ]]] * time_max_val  # Initial list with junk values to be replaced
        for t in df_tmp[time_var].sort_values().unique():
            if t > 0:
                time_list[t - 1] = (df_tmp.loc[
                    df_tmp[time_var] == t, self.coordinates].groupby(
                        self.coordinates).sum().reset_index().values.tolist())
            else:
                time_list[time_max_val] = (df_tmp.loc[
                    df_tmp[time_var] == t, self.coordinates].groupby(
                        self.coordinates).sum().reset_index().values.tolist())
        HeatMapWithTime(
            time_list,
            radius=5,
            gradient=self._grad_list,
            min_opacity=0.5,
            max_opacity=0.8,
            use_local_extrema=True,
        ).add_to(self.map)
Exemplo n.º 13
0
def setup_bike_count_heat_map(bike_data):
    bike_count_heat_map = folium.Map(location=seattle_coords,
                                     min_zoom=13,
                                     max_bounds=True)
    bike_count_heat_map.add_child(
        HeatMapWithTime(data=bike_data,
                        index=date_indices,
                        radius=50,
                        gradient={
                            0.2: 'blue',
                            0.4: 'lime',
                            0.6: 'orange',
                            1: 'red'
                        },
                        use_local_extrema=True,
                        min_opacity=0.5,
                        max_opacity=0.8))
    bike_count_heat_map.save("bike_count_heat_map.html")
Exemplo n.º 14
0
def heatmap_with_time(df_,
                      n_rows,
                      lat_origin=None,
                      lon_origin=None,
                      zoom_start=12,
                      radius=5,
                      min_opacity=0.5,
                      max_opacity=0.8,
                      base_map=None,
                      save_as_html=False,
                      filename='heatmap_with_time.html'):
    if base_map is None:
        if lat_origin is None and lon_origin is None:
            lat_origin = df_.loc[0]['lat']
            lon_origin = df_.loc[0]['lon']
        base_map = generateBaseMap(default_location=[lat_origin, lon_origin],
                                   default_zoom_start=zoom_start)
    COUNT = 'count'
    df_['hour'] = df_.datetime.apply(lambda x: x.hour)
    df_[COUNT] = 1
    df_hour_list = []
    for hour in df_.hour.sort_values().unique():
        df_hour_list.append(df_.loc[df_.hour == hour,
                                    ['lat', 'lon', COUNT]].groupby([
                                        'lat', 'lon'
                                    ]).sum().reset_index().values.tolist())

    HeatMapWithTime(df_hour_list[:n_rows],
                    radius=radius,
                    gradient={
                        0.2: 'blue',
                        0.4: 'lime',
                        0.6: 'orange',
                        1: 'red'
                    },
                    min_opacity=min_opacity,
                    max_opacity=max_opacity,
                    use_local_extrema=True).add_to(base_map)

    df_.drop(columns=[COUNT, 'hour'], inplace=True)
    if save_as_html:
        base_map.save(outfile=filename)
    else:
        return base_map
Exemplo n.º 15
0
def bushfire_spread_map():
    #Heat map object for bush fire
    bush_fire_map = folium.Map(location=[-25.2744, 133.7751], zoom_start=4)

    if request.method == 'POST':
        f = request.files['bushfire_csvfile']
        df = pd.read_csv(f)

        #group by all the rows according to date so that the map visualizes bush fires according to date
        date_groupby_list = df.groupby('date').apply(
            lambda x: x[['latitude', 'longitude']].values.tolist())
        dt_obj = [
            datetime.strptime(i, '%d-%m-%Y') for i in date_groupby_list.index
        ]
        date_index = [x.strftime('%d-%m-%Y') for x in dt_obj]
        date_hour_date = date_groupby_list.tolist()

        HeatMapWithTime(date_hour_date, index=date_index).add_to(bush_fire_map)

    return bush_fire_map.get_root().render()
Exemplo n.º 16
0
def upload():
    if request.method == 'POST':
        df_incidents = pd.read_csv(request.files.get('file'))
        #df_incidents = pd.read_csv('data.csv')
        #print('Dataset downloaded and read into a pandas dataframe!')
        df_incidents.head()
        Italy_map = folium.Map(location=[41.9028, 12.4964], zoom_start=13)
        incidents = folium.map.FeatureGroup()
        #converting latitude and longitude to float values
        df_incidents.Longitude = df_incidents.Longitude.astype(float)
        df_incidents.Latitude = df_incidents.Latitude.astype(float)

        # loop through the 100 crimes and add each to the incidents feature group

        # add incidents to map of Italy
        Italy_map.add_child(incidents)
        from folium.plugins import HeatMapWithTime
        #base_map = generateBaseMap(default_zoom_start=11)
        df_century_list = []
        for century in df_incidents.Century_of_Origin.sort_values().unique():
            df_century_list.append(
                df_incidents.loc[df_incidents.Century_of_Origin == century,
                                 ['Latitude', 'Longitude']].groupby([
                                     'Latitude', 'Longitude'
                                 ]).sum().reset_index().values.tolist())
            df_century_list
            centuries = []
            centuries = df_incidents.Century_of_Origin.sort_values().unique()
            centuries = list(centuries)
            centuries
            HeatMapWithTime(df_century_list,
                            radius=15,
                            index=centuries,
                            position='topright',
                            name='CO2 (micro-atm)',
                            control=True).add_to(Italy_map)
            Italy_map.save("Italy.html")
        return render_template('frameset.html', src1=page1, src2=page2)
    return render_template('upload.html')
Exemplo n.º 17
0
def heatmap(pollutant):
    """
    Returns a heatmap with time of the pollutant levels at each station

    Returns:
        Map: folium heatmap with time
    """
    folium_map = folium.Map(location=[46, 2.291705], zoom_start=7)
    client = DBClient("database")
    ordered_mesures = client.get_mesures_by_time(pollutant)
    global_max = get_global_max(ordered_mesures)
    heatmap_data = []
    heatmap_index = []
    for time in ordered_mesures:
        heatmap_data.append([[
            mesure["position"]["x"], mesure["position"]["y"],
            mesure["value"] / global_max
        ] for mesure in ordered_mesures[time]])
        heatmap_index.append(dt.datetime.strftime(time, "%d/%m %H:%M:%S"))
    HeatMapWithTime(heatmap_data, position="topright",
                    index=heatmap_index).add_to(folium_map)
    return folium_map
Exemplo n.º 18
0
def languages():
    '''Return data in json format'''
    df_incidents = pd.read_csv('data.csv')
    print('Dataset downloaded and read into a pandas dataframe!')
    df_incidents.head()
    Italy_map = folium.Map(location=[41.9028, 12.4964], zoom_start=13)
    incidents = folium.map.FeatureGroup()
    #converting latitude and longitude to float values
    df_incidents.Longitude = df_incidents.Longitude.astype(float)
    df_incidents.Latitude = df_incidents.Latitude.astype(float)
    # loop through the 100 crimes and add each to the incidents feature group
    # add incidents to map of Italy
    Italy_map.add_child(incidents)
    from folium.plugins import HeatMapWithTime
    #base_map = generateBaseMap(default_zoom_start=11)
    df_century_list = []
    for century in df_incidents.Century_of_Origin.sort_values().unique():
        df_century_list.append(
            df_incidents.loc[df_incidents.Century_of_Origin == century,
                             ['Latitude', 'Longitude']].groupby([
                                 'Latitude', 'Longitude'
                             ]).sum().reset_index().values.tolist())
        #df_century_list
        centuries = []
        centuries = df_incidents.Century_of_Origin.sort_values().unique()
        centuries = list(centuries)
        centuries
        HeatMapWithTime(df_century_list,
                        radius=15,
                        index=centuries,
                        position='topright',
                        name='CO2 (micro-atm)',
                        control=True).add_to(Italy_map)
        Italy_map.save("Italy.html")
        #lst = ["Python", 'HTML', 'JavaScript', 'CSS']
    #words = {}
    #words['choice'] = random.choice(lst)
    return jsonify(Italy_map)
Exemplo n.º 19
0
    def get_heatmap_video(self, 
                            radius=10, 
                            auto_play=True,
                            resolution='h', 
                            window_size=1):

        # resample
        xy = self.data[self.GPS_INDEX]
        xy = xy.resample(resolution).mean().interpolate(limit_direction='both').values

        windows = self.rolling_window(np.arange(len(xy)), window_size)
        xy = xy[windows].tolist()

        # build heatmap
        heatmap = HeatMapWithTime(xy, 
            auto_play=auto_play, 
            display_index=False, 
            radius=radius, 
            index_steps=1,
            min_speed=1, 
            max_speed=24, 
            speed_step=1)

        return heatmap
Exemplo n.º 20
0
def generate_HeatMapTime(data, location=None, zoom_start=None):
    '''
    This function generates animated Heat Map by Time based on current observations
    
    Parameters
    ----------
    data: array of arrays or so called 2-D array.
    First dimension is related to the largest Time span (e.g. months of year if the user want to create a monthly animated HeatMap).
    Second dimension is related to the second-largest Time (e.g. days of month if the user want to create a montly animated HeatMap)
    The data grouped by Time is a 3 element array-like value (e.g., an array, list, or tuple) in the order of [latitude, longitude, value]
    
    
    
    location: array [latitude, longitude], optional
    Location of center of the basemap that will be zoomed in when generating the basemap 
    By default, the location of New York City [40.693943, -73.985880] will be used
    
    zoom_start: integer, optional
    Level of zoom to the basemap. By default, value of 12 will be used
  
    Returns
    -------
    basemap
    The animated basemap in generated based on current observation. 
    The basemap will be exported as an .html 
    file and can be visualized simply by open this .html file 
            
    Examples
    -------
    >>> 
    generate_HeatMapTime(location=[40.693943, -73.985880], zoom_start=12, data=df)  
    '''
    import folium
    from folium.plugins import HeatMapWithTime

    # Default values for location and zoom levels
    if location is None:
        location = [40.693943, -73.985880]

    if zoom_start is None:
        zoom_start = 12

    # Generate the basemap by location and zoom level
    basemap = folium.Map(location=location,
                         control_scale=True,
                         zoom_start=zoom_start)

    try:
        # Generate an animated HeatMap by Time
        HeatMapWithTime(data,
                        radius=17,
                        min_opacity=0.5,
                        max_opacity=0.8,
                        use_local_extrema=True,
                        gradient={
                            0.2: 'blue',
                            0.4: 'lime',
                            0.6: 'orange',
                            1: 'red'
                        }).add_to(basemap)
    except Exception as e:
        print(e)

    basemap.save("C:/Users/tvo/Desktop/test_heatmaptime.html")
    return basemap
Exemplo n.º 21
0
def sim_folium_heat(geogridfile, griddatafile):
    #if os.path.exists(geogridfile):
    #  print( "ok esiste" )
    geogrid = gpd.read_file(geogridfile).sort_index()
    geogrid.id = geogrid.id.astype(int)
    geogrid['centroid'] = geogrid.to_crs(epsg=3857).geometry.centroid.to_crs(
        epsg=4326)
    geogrid['cen_lat'] = [p.y for p in geogrid['centroid']]
    geogrid['cen_lon'] = [p.x for p in geogrid['centroid']]

    with open(griddatafile) as gin:
        griddata = json.load(gin)

    sim_id = griddata['sim_id']
    griddata = griddata['grid_cnt']

    griddata = [{
        'timestamp': ts,
        'cell_id': int(gid),
        'cnt': val,
    } for ts, cnt in griddata.items() for gid, val in cnt.items()]
    gridcnt = pd.DataFrame.from_dict(griddata)
    #gridcnt['norm_cnt'] = (gridcnt.cnt - gridcnt.cnt.min()) / (gridcnt.cnt.max() - gridcnt.cnt.min())
    gridcnt['norm_cnt'] = gridcnt.cnt / gridcnt.cnt.max()

    #print(gridcnt)
    gridcnt = gridcnt.merge(geogrid[['id', 'cen_lat', 'cen_lon']],
                            left_on='cell_id',
                            right_on='id')

    time_label = []
    data = []
    for ts, dfg in gridcnt.groupby('timestamp'):
        #dt = f"{pd.to_datetime(ts, unit='s').tz_localize('utc').tz_convert('Europe/Rome')}"
        dt = str(
            pd.to_datetime(
                ts, unit='s').tz_localize('utc').tz_convert('Europe/Rome'))
        time_label.append(dt)
        data.append(dfg[['cen_lat', 'cen_lon', 'norm_cnt']].values.tolist())
        # print(dt, dfg.cnt.sum())

    #print(time_label)
    m = folium.Map(control_scale=True)
    _radius = 60

    if "ubrovnik" in str(geogridfile):
        _radius = 100
    HeatMapWithTime(
        data=data,
        index=time_label,
        radius=_radius,
        # gradient={'0':'Navy', '0.25':'Blue','0.5':'Green', '0.75':'Yellow', '0.85':'orange','1': 'Red'},
        gradient={
            '0': 'gray',
            '0.2': 'Blue',
            '0.4': 'Green',
            '0.6': 'Yellow',
            '0.8': 'orange',
            '1': 'Red'
        },
        # gradient={0.0: 'blue', 0.1: 'orange', 0.5: 'red'},
        min_opacity=0.2,
        max_opacity=0.6,
        use_local_extrema=False,
        display_index=True,
        auto_play=True,
    ).add_to(m)
    MeasureControl().add_to(m)
    colormap = cm.LinearColormap(
        colors=['gray', 'Blue', 'Green', 'Yellow', 'orange', 'red'],
        index=[0, 0.2, 0.4, 0.6, 0.8, 1],
        # tick_labels=[0, 25, 50, 75, 85, 100],
        caption='Density of population')
    m.add_child(colormap)

    s, w = geogrid[['cen_lat', 'cen_lon']].min()
    n, e = geogrid[['cen_lat', 'cen_lon']].max()
    m.fit_bounds([[s, w], [n, e]])
    text_save = f'{html_folder}/heatmap_{sim_id}.html'
    m.save(text_save)
    print(f'* File saved in: {text_save}')
Exemplo n.º 22
0
lon_point_list = [-0.286666667, -0.182222222, -0.3625, -0.475555556]
addpolygontomap(lat_point_list, lon_point_list, 'Luton CTA 7')

lat_point_list = [51.86388889, 51.87888889, 51.9175]
lon_point_list = [-0.726666667, -0.641111111, -0.731388889]
addpolygontomap(lat_point_list, lon_point_list, 'Luton CTA 8')

lat_point_list = [51.86388889, 51.9175, 51.96361111, 51.89888889, 51.84666667]
lon_point_list = [
    -0.726666667, -0.731388889, -0.679888889, -0.834863889, -0.823888889
]
addpolygontomap(lat_point_list, lon_point_list, 'Luton CTA 9')

lat_point_list = [
    51.87888889, 51.91972222, 51.96194444, 51.9825, 51.845, 51.80833333,
    51.75083333
]
lon_point_list = [
    -0.641111111, -0.407222222, -0.3625, -0.242777778, -0.158611111,
    -0.251666667, -0.5825
]
addpolygontomap(lat_point_list, lon_point_list, 'Luton CTR')
### Luton ###

#Now add the heatmap data
HeatMapWithTime(date_hour_data, index=date_hour_index,
                radius=8).add_to(flight_map_time)

#save it as a html
flight_map_time.save('/Users/Gareth.Ahern/Desktop/mapwithtimemapall999.html')
Exemplo n.º 23
0
#%% To change a bit I'm trying to develop in the following line a heatmap timed
from folium.plugins import HeatMap, HeatMapWithTime
import branca.colormap as cm
center = (45.74808, 4.82355)

m = folium.Map(center, zoom_start=12, tiles='OpenStreetMap')

h = folium.FeatureGroup(name='Temps de parcours')

locations = []

mamax = 100  #scaling my speed here
dimi = []
for pp in np.arange(1, 480, 1):
    locations = []
    for idx, row in Speed_and_Geom.iterrows():
        temp = row['geom'].split('|')
        for bla in temp:
            locations.append([
                float(bla.split(',')[0]),
                float(bla.split(',')[1]), row[pp] / mamax
            ])

    dimi.append(locations)

HeatMapWithTime(dimi, radius=20, gradient={0: 'green', 1: 'red'}).add_to(m)
m.add_child(h)
m.save('Timedheat.html')
#this map does not bring much with its current version, but I guess there might have potential on the next upgrade
Exemplo n.º 24
0
import math

# Importing the dataset

dataset = pd.read_csv('Vietnam_Bombing_Operations_STRIKE_HIT_YN.csv')

import folium
from folium import Choropleth, Circle, Marker
from folium.plugins import HeatMap, MarkerCluster, HeatMapWithTime

# Create a map
m_1 = folium.Map(location=[17.34, 106.71],
                 tiles='Stamen Terrain',
                 zoom_start=8)

# Add points to the map

tgtloc = []
msn_date = []
for idx, row in dataset.iterrows():
    if not math.isnan(row['TGTLONDDD_DDD_WGS84']) and not math.isnan(
            row['TGTLATDD_DDD_WGS84']):
        tgtloc.append([row['TGTLATDD_DDD_WGS84'], row['TGTLONDDD_DDD_WGS84']])
        msn_date.append(row['MSNDATE'])
# m_1.add_child(mc)

#HeatMap(data=tgtloc, radius=10).add_to(m_1)

HeatMapWithTime(data=tgtloc, index=msn_date, radius=10).add_to(m_1)
# Display the map
m_1.save('index.html')
Exemplo n.º 25
0
def get_timelapse():
    file = "static/Data/all_data.csv"
    param = "Ozone"
    # get the data
    histData = pd.read_csv(file, parse_dates=['Date'])

    histData['year'] = (histData['Date'].dt.year)
    histData['month'] = (histData['Date'].dt.month)
    histData['day'] = 1
    histData['newDate'] = pd.to_datetime(histData[['year', 'month', 'day']])

    #Reorder columns
    columns = ['newDate', 'Latitude', 'Longitude', 'AQI', 'Defining_Parameter','county_name']
    reorderData = histData[columns]
    
    # Get only the data for the parameter
    paramData = reorderData.loc[reorderData['Defining_Parameter'] == param]

    sortedhistData = paramData.sort_values(by=['newDate'])

    newhistData = sortedhistData.reset_index()
    newhistData.drop(columns=['index'], inplace=True)

    mapData=newhistData[["newDate", "Latitude", "Longitude", "AQI", 'Defining_Parameter']]
    # Create list of lists, with the "key" of the list being the date, and the "value" being all measurements for that date.
    # 1. Need list of date
    mapTime = []
    mapTime = mapData["newDate"].sort_values().unique()


    # 2. create the lists
    mapData_list = []
    
    # Weight must be between 0 and 1.  Divide AQI by max value to get correct data
    minAQI = mapData["AQI"].min()
    maxAQI = mapData['AQI'].max()

    mapData["AQI_adj"] = mapData["AQI"]/maxAQI
    
    for date in mapTime:
        mapData_list.append(mapData.loc[mapData['newDate'] == date, ["Latitude", "Longitude", "AQI_adj"]].groupby(["Latitude", "Longitude"]).mean().reset_index().values.tolist())

    # create the base map
    start_coords = (36.7378, -119.7871)
    folium_map = folium.Map(location=start_coords, zoom_start=6, tiles='stamentoner', width='80%', height='80%')

    #add the Heat Map from the data
    HeatMapWithTime(data=mapData_list, radius=20, auto_play=True, overlay=False, max_opacity=0.5,
                       gradient = {0.2: '#FBD973', 
                            0.4: '#fa782f', 
                            0.75: '#F16578', 
                            .9: '#782890'}).add_to(folium_map)
    
    title_html = "<h2>Monthly Average Ozone 2010 - 2020</h2>"
    folium_map.get_root().html.add_child(folium.Element(title_html))
    # display base map with HeatMap 
    _ = folium_map._repr_html_()
    map_id = folium_map._repr_html_()
    #map_id = folium_map.get_root().render()
    #    map_id = Markup(folium_map.get_root().html.render())
    hdr_txt = Markup(folium_map.get_root().header.render())
    script_txt = Markup(folium_map.get_root().script.render())
    folium_map.save("templates/timelapse_static.html")
    return(map_id, hdr_txt, script_txt)
Exemplo n.º 26
0
def sim_folium_heat(geogridfile, griddatafile):
    geogrid = gpd.read_file(geogridfile).sort_index()
    geogrid.id = geogrid.id.astype(int)
    geogrid['centroid'] = geogrid.to_crs(epsg=3857).geometry.centroid.to_crs(
        epsg=4326)
    geogrid['cen_lat'] = geogrid['centroid'].y
    geogrid['cen_lon'] = geogrid['centroid'].x
    #print(geogrid)

    with open(griddatafile) as gin:
        griddata = json.load(gin)['grid_cnt']

    griddata = [{
        'timestamp': ts,
        'cell_id': int(gid),
        'cnt': val,
    } for ts, cnt in griddata.items() for gid, val in cnt.items()]
    gridcnt = pd.DataFrame.from_dict(griddata)
    #gridcnt['norm_cnt'] = (gridcnt.cnt - gridcnt.cnt.min()) / (gridcnt.cnt.max() - gridcnt.cnt.min())
    gridcnt['norm_cnt'] = gridcnt.cnt / gridcnt.cnt.max()
    #print(gridcnt)
    gridcnt = gridcnt.merge(geogrid[['id', 'cen_lat', 'cen_lon']],
                            left_on='cell_id',
                            right_on='id')
    #print(gridcnt)

    time_label = []
    data = []
    for ts, dfg in gridcnt.groupby('timestamp'):
        dt = str(
            pd.to_datetime(
                ts, unit='s').tz_localize('utc').tz_convert('Europe/Rome'))
        time_label.append(dt)
        data.append(dfg[['cen_lat', 'cen_lon', 'norm_cnt']].values.tolist())
        #print(dt, dfg.cnt.sum())

    #print(time_label)
    #print(data)
    #exit()

    m = folium.Map(control_scale=True)
    HeatMapWithTime(
        data=data,
        index=time_label,
        radius=60,
        #gradient={0.0: 'blue', 0.1: 'lime', 0.3: 'orange', 0.4: 'red'},
        gradient={
            0.0: 'blue',
            0.1: 'orange',
            0.5: 'red'
        },
        min_opacity=0.2,
        max_opacity=0.6,
        use_local_extrema=False,
        display_index=True,
        auto_play=True,
    ).add_to(m)
    MeasureControl().add_to(m)
    s, w = geogrid[['cen_lat', 'cen_lon']].min()
    n, e = geogrid[['cen_lat', 'cen_lon']].max()
    m.fit_bounds([[s, w], [n, e]])
    m.save(griddatafile + '.html')
Exemplo n.º 27
0
#
#Exposure_DATA_move['adt'] = Exposure_DATA_move['adt'] + np.random.rand(len(Exposure_DATA_move)) * 1000
data_move = []
for jj in Exposure_DATA_move['hour'].sort_values().unique():
    data_move.append(Exposure_DATA_move[Exposure_DATA_move['hour'] == jj][[
        'mid_y', 'mid_x', 'adt'
    ]].groupby(['mid_y', 'mid_x', 'adt']).sum().reset_index().values.tolist())
print(data_move[0])


def generateBaseMap(default_location=[40.693943, -73.985880],
                    default_zoom_start=12):
    base_map = folium.Map(location=default_location,
                          control_scale=True,
                          zoom_start=default_zoom_start)
    return base_map


from folium.plugins import HeatMapWithTime
m = generateBaseMap(default_zoom_start=11)
HeatMapWithTime(data_move,
                radius=20,
                gradient={
                    0.45: 'blue',
                    0.4: 'lime',
                    0.4: 'orange',
                    1: 'red'
                },
                use_local_extrema=True).add_to(m)
m.save(file_path)
def initValues():


    initLabel = tk.Label(window,
                         text="Initialized Values : " "\n Location: " +  str(weather['name']) + "\n Latitude: " + str(
                             latController.get()) + "\n Longitude: " +
                              str(longController.get()) +
                              "\n Wind Speed: " + str(weather['wind']['speed'] + " mi/hr" + "\n Wind Degrees: " + str(weather['wind']['deg']) + "\n", width=18)
    initLabel.grid(row=6, column=0)


def generateBaseMap(default_location=[latController.get(), longController.get()], default_zoom_start=30):
    base_map = folium.Map(location=default_location, zoom_start=default_zoom_start)
    return base_map


from folium.plugins import HeatMap


def simulateValues():

    with open('fireVal.csv', 'w', newline='') as fp:
        fieldnames = ['latitude', 'longitude', 'count', 'minute']
        a = csv.DictWriter(fp, fieldnames=fieldnames)
        a.writeheader()

        latt = latController.get()
        longg = longController.get()
        backLat = latController.get()
        backLong = longController.get()
        duration = timeController.get() * 60
        for i in range(0, duration):  # make 4320 minutes
            fluct = randint(0, 10)
            windSpeed = randint(int(weather['wind']['speed']) - fluct, int(weather['wind']['speed']) + fluct) #needs to be fixed!
            slope = rd.uniform(0.0, 1.0)

            # variables
            Mf = randint(100, 200)
            Qig = 250 + (116 * Mf)
            E = 0.924  # fluctuating
            Pb = 0.55
            squig = 0.4824
            Ir = 62889.331
            s = 1764
            Ro = (Ir * squig) / (Pb * E * Qig)

            Ow = (0.005235)*(windSpeed*5280/60)**1.43
            Os = (17.851) * (slope ** 2)

            R = Ro * (1 + Ow + Os)

            #backing fire
            Rh = Ro*(1 + 1/Ow + Os)

            C = 7.47 * (math.exp(-0.133*(s**0.55)))
            B = 0.02526*s**0.54
            E = 0.715*(math.exp(-3.59*(10**-4)*s))
            esum = Ow + Os

            Ue = ((esum*(2.35)**E)/C)**(-B)
            z = 1 + 0.25*(Ue)
            v = ((z**2 - 1)**0.5) / z
            Rb = Rh*(1-v / 1+v)




            #wind degrees
            windDeg = weather['wind']['deg']
            fluxValue = randint(28, 95)

            #determining wind direction
            windFlux = randint(windDeg - fluxValue, windDeg + fluxValue)
            if(windFlux>= 0 and windFlux<= 29):
                windDir = "N"
            elif(windFlux> 29 and windFlux<= 65):
                windDir = "NE"
            elif(windFlux> 65 and windFlux<= 111):
                windDir = "E"
            elif (windFlux> 111 and windFlux<= 165):
                windDir = "SE"
            elif (windFlux> 165 and windFlux<= 204):
                windDir = "S"
            elif (windFlux> 204 and windFlux<= 245):
                windDir = "SW"
            elif (windFlux> 245 and windFlux<= 291):
                windDir = "W"
            elif (windFlux> 291 and windFlux<= 359):
                windDir = "NW"


            #convert to latitude/longitude using nautical miles calculation
            convert = (R / 364567.2)


            if(windDir == "N"):
                lat = latt + convert
                long = longg - convert

                lat2 = backLat - (Rb / 364567.2)
                long2 = backLong + (Rb / 364567.2)
            elif(windDir == "NE"):
                lat = latt + convert
                long = longg + convert
                lat2 = backLat - (Rb / 364567.2)
                long2 = backLong - (Rb / 364567.2)
            elif(windDir == "E"):
                lat = latt
                long = longg + convert

                lat2 = backLat
                long2 = backLong - (Rb / 364567.2)
            elif(windDir == "SE"):
                lat = latt - convert
                long = longg + convert

                lat2 = backLat + (Rb / 364567.2)
                long2 = backLong - (Rb / 364567.2)
            elif(windDir == "S"):
                lat = latt - convert
                long = longg

                lat2 = backLat + (Rb / 364567.2)
                long2 = backLong
            elif(windDir == "SW"):
                lat = latt - convert
                long = longg - convert

                lat2 = backLat + (Rb / 364567.2)
                long2 = backLong + (Rb / 364567.2)
            elif(windDir == "W"):
                lat = latt
                long = longg - convert

                lat2 = backLat
                long2 = backLong + (Rb / 364567.2)
            elif(windDir == "NW"):
                lat = latt + convert
                long = longg - convert

                lat2 = backLat - (Rb / 364567.2)
                long2 = backLong + (Rb / 364567.2)



            #convert to degrees
            a.writerow({'latitude': lat, 'longitude': long, 'count': 1, 'minute': i})
            a.writerow({'latitude': lat2, 'longitude': long2, 'count': 1, 'minute': i})

            latt = lat
            longg = long
            backLat = lat2
            backLong = long2

    df_train = pd.read_csv('fireVal.csv')
    df_test = pd.read_csv('fireVal.csv')
    df = pd.concat([df_train, df_test], sort=False, ignore_index=True)


    map = generateBaseMap(default_location=[latController.get(), longController.get()], default_zoom_start=15)

    tooltip = 'click for more info'


    folium.Marker([latController.get(), longController.get()], popup='<strong>Fire Initialization Site</strong>',
                  tooltip=tooltip,
                  icon=folium.Icon(icon='fire', color='red')).add_to(map)

    for index, row in df.iterrows():
        firetip = "Time: " + str(row['minute']) + " minutes"
        folium.CircleMarker([row['latitude'], row['longitude']],
                            radius=3,
                            fill_color="#ff0000", tooltip= firetip, color = "#32d302").add_to(map)

    from folium.plugins import HeatMap
    df_copy = df.copy()
    df_copy['count'] = 1
    HeatMap(data=df_copy[['latitude', 'longitude', 'count']].groupby(
        ['latitude', 'longitude']).sum().reset_index().values.tolist(), radius=30, gradient={0.29: 'blue', 0.63: 'lime', 0.94: 'orange', 1: 'red'}, max_zoom=13).add_to(
        map)

    df_min_list = []
    for minute in df_copy.minute.sort_values().unique():
        df_min_list.append(df_copy.loc[df_copy.minute == minute, ['latitude', 'longitude', 'count']].groupby(
            ['latitude', 'longitude']).sum().reset_index().values.tolist())

    from folium.plugins import HeatMapWithTime
    HeatMapWithTime(df_min_list, radius=45, gradient={0.2: 'red', 0.4: 'orange', 0.6: 'lime', 1: 'blue'},
                    min_opacity=0.5, max_opacity=0.8, use_local_extrema=True).add_to(map)

    map.save("fireSimu.html")

    url = "/Users/shrinandan-n/PycharmProjects/WildfireSimulation/fireSimu.html"


    webbrowser.open(url)


# simulate values button
simuBtn = tk.Button(window, text="SIMULATE VALUES", fg="blue", width=15,
                    command=simulateValues)  # , command=recieverValues
simuBtn.grid(row=5, column=1)
initBtn = tk.Button(window, text="INITIALIZE VALUES", fg="red", width=15,
                    command=initValues)  # , command=recieverValues
initBtn.grid(row=5, column=0)


window.mainloop()
Exemplo n.º 29
0
    time = row['date_start']
    iframe = folium.IFrame(table('Deaths', name, deaths, time),
                           width=width,
                           height=height)
    popups[year].append(iframe)

h = folium.FeatureGroup(name='Deaths')
print(len(locations))
print(len(popups))
#for year in tqdm(conflict_df.date_start.unique()-1989):
#
#    mc = MarkerCluster(locations=locations[year], popups=popups[year], overlay=True, control=True)
#    mc.add_to(m)
#folium.LayerControl().add_to(m)

h.add_child(FastMarkerCluster(locations))
#m.add_child(h)
m.save(os.path.join('results', "output_map.html"))

m = folium.Map(tiles='cartodbpositron', world_copy_jump=True, no_wrap=True)

event_list = conflict_df[["latitude", "longitude", "best", "date_start"]]
list_of_event = [[row.latitude, row.longitude, row.best]
                 for row in event_list.itertuples()]
date_list = [row.date_start for row in event_list.itertuples()]
hm = HeatMapWithTime(data=list_of_event[:100],
                     index=event_list.date_start[:100],
                     max_opacity=0.3)
hm.add_to(m)
m.save(os.path.join('results', "output_map_heat.html"))
Exemplo n.º 30
0
                [-37.8190, 144.9682,
                 float(Princes_Bridge[i]) / 3000],  #
                [
                    -37.8181, 144.9670,
                    float(Flinders_St_Station_Underpass[i]) / 3000
                ],
                [-37.8202, 144.9629,
                 float(Sandridge_Bridge[i]) / 3000]
            ]
            Data.append(data)
        except (ValueError):
            print(Time[i])
        i = i + 1
    HeatMapWithTime(Data,
                    name="墨尔本人行道人流情况",
                    auto_play=True,
                    radius=40,
                    index=Time,
                    min_speed=1,
                    max_speed=24).add_to(m)
    m.add_child(folium.LatLngPopup())
    i = 0
    print(len(data))
    print(len(AD))
    while (i + 7) < len(AD) / 9:
        folium.Marker([data[i][0], data[i][1]], popup=AD[i + 7]).add_to(m)
        i = i + 1
    m.save("墨尔本人行道人流情况.html")
    foliumacc.rr("墨尔本人行道人流情况.html")
    webbrowser.open("墨尔本人行道人流情况.html")